How to access property names that contain numbers within a loop? - javascript

I want to access values of below elments
opener.document.EditView.flight_no1_c.value
opener.document.EditView.flight_no2_c.value
opener.document.EditView.flight_no3_c.value
opener.document.EditView.flight_no4_c.value
Here only numbers are changing ranging from 1 to 4.
How can I make this into loop.

You can use for loop and call properly using [] insteand on ., see below code
for(var i = 1; i <= 4; i++ ){
opener.document.EditView["flight_no"+i+"_c"].value
}

what about
for(var key in opener.document.EditView){
if(key.match(/^flight_no\d+_c/)){
console.log(key.value);
}
}

Related

how can I pop all array list

ı couldn't pop() every array list. at the end remain two array elements
function ürünSil(){
let diller = [ "Türkçe", "İngilizce", "Almanca", "Fransızca", "Japonca"]
for(let i in diller){
let sonİcerik = diller.pop()
document.write(diller + "<br />")
}
}
you can empty your array like this also:
let diller = [ "Türkçe", "İngilizce", "Almanca", "Fransızca", "Japonca"];
while(diller.length > 0) {
diller.pop();
}
console.log(diller)
The length of the array changes each time on pop() so when there are 3 items removed from the array , the present index for i on your code will be 2 and hence the actual length is also 2, so the for() loops does not trigger further.
The solution could be to preserve the initial length value and use that value in the loop:
function ürünSil(){
let diller = [ "Türkçe", "İngilizce", "Almanca", "Fransızca", "Japonca"]
const length = diller.length;
for(let i = 0; i<length; i++){
let sonİcerik = diller.pop()
console.log(sonİcerik);
}
}
ürünSil()
use while loop instead of for.
while (diller.length != 0) {
diller.pop();
document.write(diller + '<br />');
}
This happens because pop reduces the length of the array, which impacts the times the loop will iterate. Instead just have the while condition check whether the array still has elements, without any i.
Unrelated, but
don't use document.write for this. Use console.log, or if you want to add data to the HTML document, then use other DOM methods.
have the good habit of ending your statements with semicolon. You don't want to fall for the sometimes tricky effects of automatic semicolon insertion.
let diller = [ "Türkçe", "İngilizce", "Almanca", "Fransızca", "Japonca"];
while (diller.length) {
let sonİcerik = diller.pop();
console.log(sonİcerik);
}

Duplicate one array of objects in multiple arrays

I want to duplicate one array of objects into multiple ones, because every one of them I need to use in separate places.
if(!this.tempLookups){
for (let count = 0; count < this.dates.length; count++) {
this.tempLookups[count] = this.lookups[key];
}
}
Error: Uncaught (in promise) TypeError: Cannot set property '0' of null
The actual reason for the error is clearly in error message that you are trying to set the property for a null. So in order to fix simply define it after the if.
if(!this.tempLookups){
his.tempLookups = [];
for (let count = 0; count < this.dates.length; count++) {
this.tempLookups[count] = this.lookups[key];
}
}
You can do it in a single line without a for loop using Array#fill method since you are filling with the same value.
if(!this.tempLookups){
this.tempLookups = new Array(this.dates.length).fill(this.lookups[key]);
}
You can do this like this:
if (!this.tempLookups) {
this.tempLookups = [];
for (let i = 0; i < this.dates.length; i++) {
this.tempLookups.push(Array.from(this.lookups[key]));
}
}
Note that the this.tempLookups variable is initialized as empty array before we start inserting data. The Array.from call in for loop makes sure we actually create (shallow) copies of the this.lookups[key] array, instead of just assigning reference to the same this.lookups[key] array multiple times. Without Array.from changing one array would change all of them - because in reality there would be only one array referenced multiple times.

Array.splice inside a for loop causing errors

im using Angular ng-repeat to display $scope.currentMessageList array
i also have a remove button bound via ng-click to the remove function, which looks like this:
remove: function () {
for (var i = 0; i < 25; i++) {
var index = i;
$scope.currentMessageList.splice(index, 1);
console.log($scope.currentMessageList.length + 'left');
}
}
There are 25 items in this collection, when I call the remove function,
I get this output:
24left
23left
22left
21left
20left
19left
18left
17left
16left
15left
14left
13left
13times X 12left
If I replace the for loop with angular.forEach
I get "12 left" only once, still it doesn`t remove more than 13 items
Ive also tried to use angular.apply, than I get digest already in progress error
Performing a splice while iterating through an array is a bad idea.
You should replace
for( var i = 0; i < 25; i++ ){
var index = i;
$scope.currentMessageList.splice( index, 1 );
console.log($scope.currentMessageList.length + 'left');
}
by a simple
$scope.currentMessageList.splice( 0, 25 );
You're removing items while walking the array.
When you reach half of the array you've already removed half the items, so you won't remove anything else.
You can fix this either by always removing the first item or by iterating backwards from 24 towards 0.
When you remove array items in loop, indexes get shifted too. As the result you can iterate over only the half of them. This is the issue here.
If you want to clear 25 first items you can remove them with Array.prototype.shift method instead. In this case it will remove the first element of the array 25 times, giving you expected result:
remove: function () {
for (var i = 0; i < 25; i++) {
currentMessageList.shift();
}
}
When you splice the array.. the length of the array changes.
When you are trying to remove the element at index 13, the length is 12 only.
Hence it is not removed.
Instead of splice, try shift();
You don't need to iterate over your array to remove all the items. Just do this:
remove : function(){
$scope.currentMessageList = [];
}
Check out this answer also. There are others way to achieve this that are also valid.

Javascript array + index

Im still needing help with this, and have edited the jsfiddle post to show my problem. http://jsfiddle.net/7ztEf/6/
I want to return number to associated index value [0] =0 [1]=1 as you can see the index string returns all numbers. Thanks again Paul
I have a number generator script that returns values to DIV ID's. I need to hook into this somehow, to enable replacing color based upon the number value i.e. > 1 && <= 20 = red etc.
function myNumbers(numbers, type) {
for (var x in numbers) {
document.getElementById(type + x).innerHTML = numbers[x];
}
}
This script fills each of the DIVs named num0 ... num3 with a random number.
I have managed to query the first value of numbers[x] but need to set an index order to loop through the rest, or something.
Use Array.forEach.
numbers.forEach(function (number, index) {...})
Don't use for..in for arrays. They're meant to be used on objects so using for..in on arrays will return such things as the length element.
Either use forEach as ethagnawl mentioned or use the traditional for loop:
for (var x=0; x < numbers.length; x++) {
document.getElementById(type + x).innerHTML = numbers[x];
}

Code doesn't work in foreach

Here is my code:
var divarray = document.getElementById("yui-main").getElementsByTagName("div");
var articleHTML;
var absHTML;
var keyHTML;
var bodyHTML = [];
for( var i in divarray) {
if(divarray[i].className == "articleBody"){
articleHTML = divarray[i];
for( var j in articleHTML ){
bodyHTML[i] = '';
if(articleHTML[j].className == "issueMiniFeature"){continue;}
if(articleHTML[j].className == "abstract"){absHTML = articleHTML[i]; continue;}
if(articleHTML[j].className == "journalKeywords"){keyHTML = articleHTML[i]; continue;}
bodyHTML[i] = articleHTML[i];
}
break;
}
i++;
}
The error I am getting is:
SyntaxError: Unexpected token var
I am using Google Chrome
The javascript for...in doesn't do what you would expect (which is enumerate through eleemnts in an array.
for...in in javascript will enumerate through the key/value pairs (or public variables) that make up the object (which isn't what you want).
You need to use a good, old fashioned for loop.
You can add this to your script:
Array.prototype.foreach = function (callback) {
for (var i=0; i < this.length; i++) {
callback(this[i]);
}
}
Then you simply do this:
myarray.foreach(function (currentItem) {
/*...do whatever with the currentItem...*/
});
I think you mistaking JavaScript for the functionality of PHP. JavaScript does not have foreach loops. JavaScript has for in, which is what you are incorrectly using and normal for loops. Use a standard for loop when dealing with arrays. You will need to use a for in loop with object literals because the index is not the simplicity of an incrementing positive integer.
In JavaScript a for loop has 3 parts in its argument separated by a semicolon as follows:
* start position of incrementor (optional if the variable is previous defined with 0 or a positive integer)
* end position of incrementor
* method of incrementation
In the following examples arrayName is value I made up for the name of an array:
for (; a < arrayName.length; a += 1) {
for (a = x + 1; a < arrayName.length + 3; a += 2) {
The for in loop argument has two required parts and a third part to prevent errors using an if condition:
* The value of an index to search for
* The name of the container in which to search
* The third part is an if condition
The following example will return the value supplied to the "book" index of the objectName object literal. objectName is a name I made for an example object literal:
for ("book" in objectName) {
if (objectName.hasProperty("book")) {
Why not use a traditional for loop instead? You're not really using an associative array here ...
That's not the right way to iterate over a collection.
You want a standard for loop, not a for..in loop
for( var i = 0, l = divarray.length; i < l; i++ ) {
There's something else, you then proceed to try to iterate over each element
for( var j in articleHTML ){
articleHTML at this point holds a reference to a single HTML node - not a collection or array of any sort.

Categories