为什么“forEach 不是函数"?对于这个对象? [英] Why is "forEach not a function" for this object?

查看:28
本文介绍了为什么“forEach 不是函数"?对于这个对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能真的很愚蠢,但我不明白为什么这不起作用.

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);
});

未捕获的类型错误:a.forEach 不是函数

http://jsfiddle.net/ty7z6pse/

推荐答案

Object 没有 forEach,它属于 Array 原型.如果要遍历对象中的每个键值对并取值.你可以这样做:

Object does not have forEach, it belongs to Array prototype. If you want to iterate through each key-value pair in the object and take the values. You can do this:

Object.keys(a).forEach(function (key){
    console.log(a[key]);
});

使用说明:对于一个对象 v = {"cat":"large", "dog": "small", "bird": "tiny"};, Object.keys(v) 给你一个键数组,所以你得到 ["cat","dog","bird"]

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"]

这篇关于为什么“forEach 不是函数"?对于这个对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆