我想知道是否有一种方法可以在JavaScript中做一些类似PHP foreach循环的事情。我正在寻找的功能是类似这样的PHP代码片段:

foreach($data as $key => $value) { }

我在看JS for. in循环,但似乎没有办法指定as。如果我用一个'normal' for循环(for(var I = 0;I < data.length;i++),有办法抓取键=>值对吗?


当前回答

var global = (function() {
   return this;
})();

// Pair object, similar to Python

function Pair(key, value) {
    this.key = key;
    this.value = value;

    this.toString = function() {
       return "(" + key + ", " + value + ")";
    };
}

/**
 * as function
 * @param {String} dataName A String holding the name of your pairs list.
 * @return {Array:Pair} The data list filled
 *    with all pair objects.
 */
Object.prototype.as = function(dataName) {
    var value, key, data;
    global[dataName] = data = [];

    for (key in this) {
       if (this.hasOwnProperty(key)) {
          value = this[key];

          (function() {
             var k = key,
                 v = value;

            data.push(new Pair(k, v));
          })();
       }
    }

    return data;
};

var d = {
   'one': 1,
   'two': 2
};

// Loop on your (key, list) pairs in this way
for (var i = 0, max = d.as("data").length; i < max; i += 1) {
   key = data[i].key;
   value = data[i].value;

   console.log("key: " + key + ", value: " + value);
}

// delete data when u've finished with it.
delete data;

其他回答

请尝试以下代码:

<script> 
 const games = {
  "Fifa": "232",
  "Minecraft": "476",
  "Call of Duty": "182"
 };

Object.keys(games).forEach((item, index, array) => {
  var msg = item+' '+games[item];
  console.log(msg);
});

没有人提到Object。钥匙,所以我会提到它。

Object.keys(obj).forEach(function (key) {
   // do something with obj[key]
});

下面是一个非常接近的例子。

for(var key in data){
  var value = data[key];    
  //your processing here
}

如果你正在使用jQuery,请访问:http://api.jquery.com/jQuery.each/

for (var k in target){
    if (target.hasOwnProperty(k)) {
         alert("Key is " + k + ", value is " + target[k]);
    }
}

hasOwnProperty用于检查目标是否真的具有该属性,而不是从其原型继承该属性。更简单的说法是:

for (var k in target){
    if (typeof target[k] !== 'function') {
         alert("Key is " + k + ", value is" + target[k]);
    }
}

它只是检查k是不是一个方法(如果目标是数组,你会得到很多方法的警告,例如indexOf, push, pop等)。

有三个选项来处理对象的键和值:

选择值: Object.values (obj)。forEach(value =>…); 选择键: 种(obj)。forEach(key =>…); 选择键和值: Object.entries (obj)。forEach(([key, value]) =>…