JavaScript foreach键值数组

JavaScript foreach Key Value array

本文关键字:数组 键值 foreach JavaScript      更新时间:2023-09-26

我有这个数组:

var sArray = {856:"users", 857:"avatars", 858:"emails"};

,我想用forEach的方式来获取键和值:

key = 856
value = user

我的$.each代码没有返回我期望的结果,而我得到:

856:user

我必须与:分开,从这个数组中获得键和值。

我的代码是:
$.each(template_array, function(key, value) {
    console.log("key: " + "value: " + value);
});

如何访问键和值没有分开?

仅取Object.keys作为键,Array.prototype.forEach作为纯Javascript中的值。

var sArray = { 856: 'users', 857: 'avatars', 858: 'emails'};
Object.keys(sArray).forEach(function (key) {
    document.write('key: ' + key + ', value: ' + sArray[key] + '<br>');
});

使用+将它们连接起来

var template_array = {
  856: 'users',
  857: 'avatars',
  858: 'emails'
};
$.each(template_array, function(key, value) {
  console.log('key:' + key + ', value:' + value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

更新:我认为你有一个数组然后使用下面的代码

var template_array = ['856: users',
  '857: avatars',
  '858: emails'
];
template_array.forEach(function(v) {
  v = v.split(':');
  console.log('key:' + v[0] + ', value:' + v[1]);
});

试试这个

var template_array = {
   856: 'users',
   857: 'avatars',
   858: 'emails'
};
var date = [];
$.each(template_array,function (key , val){ 
   date.push({key:key, value:val})
 });
console.log(date)

var template_array = {
  856: 'users',
  857: 'avatars',
  858: 'emails'
};
for (key in template_array) {
  console.log('key:' + key + ', value:' + template_array[key]);
});