在 Javascript 上使用 for ( in ) 循环与 ColdFusion 不匹配
looping with for ( in ) on Javascript does not match ColdFusion
在 ColdFusion 中,我可以做到这一点
<cfscript>
favorites = [{"broker_label":"spectra"}];
for (afav in favorites) {
writedump(afav);
}
</cfscript>
然后我得到数组中的每一行。
如果我在 Javascript
中尝试这个
favorites = [{"broker_label":"spectra"}];
for (var afav in favorites) {
console.log(JSON.stringify(afav));
}
而我得到的只是 0,或者准确地说。 "\"0\""
这是怎么回事?
ColdFusion return 数组中的每个元素。
Javascript return 数组中元素的索引。为了获得类似的结果,我必须
for (var afav in favorites) {
console.log(JSON.stringify(favorites[afav]));
}
如果你想迭代数组的值,你可以使用 for…of
or array.forEach()
favorites = [{"broker_label":"spectra"}];
for (let fav of favorites) {
console.log(JSON.stringify(fav));
}
// or:
favorites.forEach(elem => console.log(JSON.stringify(elem)))
for…in
迭代属性,在数组的情况下是索引。请注意,当顺序很重要时,不鼓励对数组使用 for…in
:
来自https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in:
Note: for...in should not be used to iterate over an Array where the index order is important.
在 ColdFusion 中,我可以做到这一点
<cfscript>
favorites = [{"broker_label":"spectra"}];
for (afav in favorites) {
writedump(afav);
}
</cfscript>
然后我得到数组中的每一行。
如果我在 Javascript
中尝试这个favorites = [{"broker_label":"spectra"}];
for (var afav in favorites) {
console.log(JSON.stringify(afav));
}
而我得到的只是 0,或者准确地说。 "\"0\""
这是怎么回事?
ColdFusion return 数组中的每个元素。
Javascript return 数组中元素的索引。为了获得类似的结果,我必须
for (var afav in favorites) {
console.log(JSON.stringify(favorites[afav]));
}
如果你想迭代数组的值,你可以使用 for…of
or array.forEach()
favorites = [{"broker_label":"spectra"}];
for (let fav of favorites) {
console.log(JSON.stringify(fav));
}
// or:
favorites.forEach(elem => console.log(JSON.stringify(elem)))
for…in
迭代属性,在数组的情况下是索引。请注意,当顺序很重要时,不鼓励对数组使用 for…in
:
来自https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in:
Note: for...in should not be used to iterate over an Array where the index order is important.