Javascript 为什么此对象的“forEach 不是函数”?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31096596/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why is "forEach not a function" for this object?
提问by haventchecked
This is probably something really dumb, but I don't understand why this doesn't work.
这可能是非常愚蠢的事情,但我不明白为什么这不起作用。
var a = {"cat":"large"};
a.forEach(function(value, key, map){
console.log(value);
});
Uncaught TypeError: a.forEach is not a function
未捕获的类型错误:a.forEach 不是函数
回答by TaoPR
Object does not have forEach, it belongs to Arrayprototype. If you want to iterate through each key-value pair in the object and take the values. You can do this:
对象不具备forEach的,它属于以Array原型。如果要遍历对象中的每个键值对并取值。你可以这样做:
Object.keys(a).forEach(function (key){
console.log(a[key]);
});
Usage note: For an object v = {"cat":"large", "dog": "small", "bird": "tiny"};, Object.keys(v)gives you an array of the keys so you get ["cat","dog","bird"]
使用说明:对于一个对象v = {"cat":"large", "dog": "small", "bird": "tiny"};,Object.keys(v)给你一个键数组,所以你得到["cat","dog","bird"]
回答by Ahmed Younes
When I tried to access the result from
当我尝试访问结果时
Object.keys(a).forEach(function (key){
console.log(a[key]);
});
Object.keys(a).forEach(function (key){
console.log(a[key]);
});
it was plain text result with no key-value pairs Here is an example
这是没有键值对的纯文本结果这是一个例子
var fruits = {
apple: "fruits/apple.png",
banana: "fruits/banana.png",
watermelon: "watermelon.jpg",
grapes: "grapes.png",
orange: "orange.jpg"
}
Now i want to get all links in a separated array , but with this code
现在我想在一个单独的数组中获取所有链接,但是使用此代码
function linksOfPics(obJect){
Object.keys(obJect).forEach(function(x){
console.log('\"'+obJect[x]+'\"');
});
}
the result of :
的结果 :
linksOfPics(fruits)
"fruits/apple.png"
"fruits/banana.png"
"watermelon.jpg"
"grapes.png"
"orange.jpg"
undefined
I figured out this one which solves what I'm looking for
我想出了这个解决了我正在寻找的问题
console.log(Object.values(fruits));
["fruits/apple.png", "fruits/banana.png", "watermelon.jpg", "grapes.png", "orange.jpg"]

