Why is “forEach not a function” for this object?

后端 未结 3 1605
梦毁少年i
梦毁少年i 2020-12-13 05:58

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){
           


        
3条回答
  •  旧时难觅i
    2020-12-13 06:32

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

提交回复
热议问题