为什么“forEach不是一个函数”这张地图? [英] Why is "forEach not a function" for this map?

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

问题描述

  var a = { 猫: 大}; 
$ b $ a.forEach(function(value,key,map){
console.log(value);
});

未捕获的TypeError:a.forEach不是函数



http://jsfiddle.net/ty7z6pse/

解决方案

对象没有 forEach ,它属于 Array prototype 一>。如果要遍历对象中的每个键值对,并取值。你可以这样做:

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

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


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

http://jsfiddle.net/ty7z6pse/

解决方案

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

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天全站免登陆