有一个带有数组参数的函数。对我来说,必须推断出对象中通过符号“-”的值。例: [“ BMW-55 000-德国-高”,“ Mitsubishi-93 000-Bar John-3-Japan”,“ Mercedes-benz-63 000-德国-高”。错误在哪里?
const car = [
{
"name":"BMW",
"price":"55 000",
"country":"Germany",
"security":"Hight"
},
{
"name":"Mitsubishi",
"price":"93 000",
"constructor":"Bar John",
"door":"3",
"country":"Japan",
},
{
"name":"Mercedes-benz",
"price":"63 000",
"country":"Germany",
"security":"Hight"
}
];
function joinArr(car){
return Object.values(car).forEach(function(){
return car.join("-")
});
}
答案 0 :(得分:2)
您可以使用map
遍历数组。使用Object.values
将对象转换为数组。
const car = [{"name":"BMW","price":"55 000","country":"Germany","security":"Hight"},{"name":"Mitsubishi","price":"93 000","constructor":"Bar John","door":"3","country":"Japan"},{"name":"Mercedes-benz","price":"63 000","country":"Germany","security":"Hight"}];
function joinArr(car) {
return car.map(o => Object.values(o).join("-"));
}
var result = joinArr(car);
console.log(result);
答案 1 :(得分:1)
car
不是对象,而是对象的数组。您可能希望将其映射(并将car
重命名为cars
以避免混淆):
function joinCars(cars) {
return cars.map(function(car) {
return Object.values(car).join("-");
});
}
答案 2 :(得分:0)
forEach
不返回任何内容-只需使用join
:
function joinArr(car){
return Object.values(car).join("-");
}
要对整个数组执行此操作并获取字符串数组,请使用map
。还可以考虑重命名参数:
const car = [
{
"name":"BMW",
"price":"55 000",
"country":"Germany",
"security":"Hight"
},
{
"name":"Mitsubishi",
"price":"93 000",
"constructor":"Bar John",
"door":"3",
"country":"Japan",
},
{
"name":"Mercedes-benz",
"price":"63 000",
"country":"Germany",
"security":"Hight"
}
];
const joinArr = cars => cars.map(car => Object.values(car).join("-"));
console.log(joinArr(cars));