best way to use "for in" [duplicate] - javascript

This question already has answers here:
Why is using "for...in" for array iteration a bad idea?
(28 answers)
JavaScript: Why does the "for in" loop pick variables from __proto__?
(4 answers)
Loop through an array in JavaScript
(46 answers)
Loop (for each) over an array in JavaScript
(40 answers)
Closed 8 months ago.
The code which worked before was failing now in for loop after I added enyo.js. I suspect that when I use for(var ls in list) it loops through even when length is 0. When I put the debugged I found out that it is considering "findIndex" as one of value in list and goes into the loop. I have several places using for with in, I want to find out a best way to filter out "findIndex" or any invalid indexes so that only valid elements go into the loop
for(var ls in list)
{
var lin = list[ls].rb ;
}

If you list is an array, just use a regular for loop. It's generally not a great idea to use for...in with an array for exactly this reason and also because the order isn't guaranteed.
If you must use for...in use a hasOwnProperty check:
for (var ls in list)
{
if (list.hasOwnProperty(ls)) {
var lin = list[ls].rb;
// ...
}
}
Of course, if you only concern is whether you have an rb property, you could just test for that:
if (list[ls].rb) {
var lin = list[ls].rb;
}
Or even:
var lin = list[ls].rb;
if (lin) {
// do whatever you needed to do with lin
}

Related

How to let user defined mehods not being iliterated in a for in statement [duplicate]

This question already has answers here:
Why is using "for...in" for array iteration a bad idea?
(28 answers)
How to define method in javascript on Array.prototype and Object.prototype so that it doesn't appear in for in loop
(4 answers)
Closed 1 year ago.
This is the piece code to show my question:
var data=[];
for(var pro in data) {
console.log('Property: '+pro);
}
Array.prototype.Dummy=function() {
};
for(var pro in data) {
console.log('Property:'+pro);
}
I expect the 2 for in statements behave the same, the first prints nothing, reasonable, but the second one will list 'Dummy' only as the array's property, even Array has lots of buildin methods.
The user defined method is different from build in, why?
The reason I ask this question is that I use 3 party libraries, if I extend buildin data types(like Array, Date ect.), I'll potentially modify what their for in statements do.

What is wrong with for(let key in obj) in javascript? IDE warnings seem redundant [duplicate]

This question already has answers here:
JavaScript Possible Iteration Over Unexpected
(5 answers)
Why is using "for...in" for array iteration a bad idea?
(28 answers)
Closed 5 years ago.
I use phpstorm and over the past half a year or so it started warning me about code like this:
for( let key in attachmentPaths ){
requestObject.formData.attachments.push( fs.createReadStream(attachmentPaths[key]) )
}
Warning on [key]
Possible iteration over unexpected (custom/inherited) members,
probably missing hasOwnProperty check
I understand the warning message, but i don't understand how a for() like this is bad?
Surely additional checks to ensure the key exists with the object is silly as we are looping over the objects found keys..?
Surely additional checks to ensure the key exists with the object
That isn't what the error message says.
The important part is "unexpected (custom/inherited) members".
You could find yourself dealing with extra properties that you weren't expecting which are inherited on the prototype chain.
Consider:
Object.prototype.surprise = "surprise!";
var foo = {
a: 1,
b: 2
};
for (var bar in foo) {
console.log(bar, foo[bar]);
}
You have to check if the object has key if you want to use for in loop.
In javascript, everything is an object. You can assign functions to variables as well. With for ... in loop you are iterating all keys the object has. So if the object has a function that is assigned to a key in the object, you might try to iterate that as well (like the built in functions in strings/arrays etc.)
for( let key in attachmentPaths ){
if(attachmentPaths.hasOwnProperty(key){
requestObject.formData.attachments.push( fs.createReadStream(attachmentPaths[key]) )
}
}

Struggling with Javascript Object Array adding keys [duplicate]

This question already has answers here:
Add a property to a JavaScript object using a variable as the name? [duplicate]
(14 answers)
Closed 5 years ago.
I have this snippet of code:
var arrLiteData = [];
for(ii=0;ii<10;ii++)
{
arrLiteData.push({ii:{"field1":100,"field2":ii}});
}
...but instead of ii taking the increasing numeric value of ii, the array just holds the actual variable name, like this:
[{"ii":{"field1":100,"field2":0}},{"ii":{"field1":100,"field2":1}}...etc, etc...
What am I doing wrong?
Many thanks.
Quotes are optional for javascript object keys, so
{ii:{"field1":100,"field2":ii}} is the same as
{"ii":{"field1":100,"field2":ii}} or even
{ii:{field1:100,field2:ii}}. They are just need if you have non alphanumeric characters.
To solve this you could either use a computed key if you're transpiling your code or targeting recent navigators:
{[ii]:{"field1":100,"field2":ii}}
Or build the object in two steps:
var arrLiteData = [];
for(ii=0;ii<10;ii++)
{
var obj = {};
obj[ii] = {"field1":100,"field2":ii};
arrLiteData.push(obj);
}

ie javascript for in loop vs chrome for in loop [duplicate]

This question already has answers here:
IE8 for...in enumerator
(3 answers)
How do I check if an object has a specific property in JavaScript?
(31 answers)
Closed 8 years ago.
var arr=["test"]; for(var e in arr) console.log(e);
in IE11's console it outputs:
0 contains remove clear add addAll(all properties)
and in chrome's console only outputs 0, which is expected.
how to fix it in IE? I know I can use for(var i=0;i<arr.length;i++) to solve it.
but I just wonder why IE outputs all the properties.
using IE11 and looks ok to me
if you want more control use Array.prototype.forEach method.It accepts a callback which have three parameters.They are element,their index and the array itself.Try
var arr=["test",'ball'];arr.forEach(function(element,index){
console.log(index);
});
Use the hasOwnProperty method.
Example:
var arr = ["test"];
for (var e in arr) {
if (arr.hasOwnProperty(e)) {
console.log(e);
}
}
Good explanation on why this is necessary: https://stackoverflow.com/a/12017703/1387396
Details on the hasOwnProperty method and its use in for .. in loops: Object.prototype.hasOwnProperty() - JavaScript | MDN

Getting the length of a 'named' array? [duplicate]

This question already has answers here:
Length of a JavaScript object
(43 answers)
Closed 9 years ago.
I'm not sure what they are called, but what I mean is this:
array["water"] = 50;
array["fire"] = 30;
length should be 2 here
how can I see how many attributes I have in the array? array.length doesn't work =( I've been trying all kinds of things and I feel like I'm missing something really simple here..
Thank you for your help
You could use Object.keys() to obtain an array of keys, then count them:
Object.keys(array).length
Or, if you're targeting ECMAScript 3 or otherwise don't have Object.keys(), then you can count the keys manually:
var length = 0;
for (var key in array) {
if (array.hasOwnProperty(key)) {
++length;
}
}
There are a few edge cases with this approach though, depending on the browsers you're targeting, so using Mozilla's polyfill for Object.keys() instead might be a good idea.

Categories