Return 不使用 Object.entries() 的键值对数组的数组

Return an array of arrays of key-value pairs WITHOUT using Object.entries()

我正在尝试编写一个接受对象和 return 键值对数组的函数。我也不能使用 Object.entries() 函数。

示例:对于 var obj = { a: 1, b: 2, c: 3 }; 我想要 return:[["a",1], ["b",2], ["c",3]]

这是我到目前为止所写的内容:

function entries(obj) {

var result = Object.keys(obj).map(function(key) {
  return [Number(key), obj[key]];
});
}
console.log(
  entries(obj = {"1":5,"2":7,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0})
  );

不过,我现在只能把它变成return undefined。我到底做错了什么?

您忘记 return 最后 result 来自 entries()

function entries(obj) {
  var result = Object.keys(obj).map(function(key) {
      return [Number(key), obj[key]];
    });
    return result;
}
console.log(
  entries(obj = {"1":5,"2":7,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0})
  );

你可以做一个简单的 for 循环

var obj= {"1":5,"2":7,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0}
var arr=[]
for(var item in obj){
  arr.push([item,obj[item]])
}
console.log(arr)

首先让我们分析您的代码并检测一些错误,然后我们将专注于解决方案。

function entries(obj) {
  var result = Object.keys(obj).map(function(key) {
    return [Number(key), obj[key]];
  });
}
console.log(
  entries(obj = {"1":5,"2":7,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0})
);

在您的代码中,函数 entries 没有 return 任何值。因此,console.log()将returnundefined。我们可以解决此问题,将 var result = 替换为 return。所以现在你的 entries 函数 return 是一个基于你的对象 obj 的数组。像这样:

function entries(obj) {
  return Object.keys(obj).map(function(key) {
    return [Number(key), obj[key]];
  });
}
console.log(
  entries(obj = {
    "1": 5,
    "2": 7,
    "3": 0,
    "4": 0,
    "5": 0,
    "6": 0,
    "7": 0,
    "8": 0,
    "9": 0,
    "10": 0,
    "11": 0,
    "12": 0
  })
);

现在我们可以稍微优化一下让我们定义两个对象:objAobjB。第一个将是您的第一个示例。

let objA = { a: 1, b: 2, c: 3 };
let objB = {"1":5,"2":7,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0};

如果你调用 console.log(entries(objA)) 你会得到一个 NaN 错误,因为 a 不是一个数字并且你正在使用 Number() 方法来转换 key 值。让我们删除该函数调用。这将是解决方案的最终版本:

let objA = { a: 1, b: 2, c: 3 };
let objB = {"1":5,"2":7,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0};

function entries(obj) {
  return Object.keys(obj).map(function(key) {
    return [key, obj[key]];
  });
}

console.log(entries(objA));
console.log(entries(objB));