我有一个将数组转换为数组对象的代码
const thisArray = ['1', '2'];
下面是我的转换它的函数:
function macsFunction(codes){
const mappedObjects = codes.map(code => {
return {
'0': Number(code),
'1': 'Car'
};
});
return mappedObjects;
}
const thisSay = macsFunction(thisArray);
console.log(thisSay);
结果是这样的:
[ { '0': 5, '1': 'Car' }, { '0': 13, '1': 'Car' } ]
现在我已经花了很长时间来实现这样的目标:
[null, { '0': 5, '1': 'Car' }, { '0': 13, '1': 'Car' } ]
我想在数组的开头放置一个null
。但我尝试过concat
、fill
、unshift
。这不起作用。很高兴看到是否有人可以提供帮助。
最佳答案
您可以使用Array.prototype.unshift()
它将一个或多个元素添加到数组的开头:
const thisArray = ['1', '2'];
function macsFunction(codes){
const mappedObjects = codes.map(code => {
return {
'0': Number(code),
'1': 'Car'
};
});
mappedObjects.unshift(null);
return mappedObjects;
}
const thisSay = macsFunction(thisArray);
console.log(thisSay);
关于javascript - 将 null 放置在数组的开头,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50989153/