我有一个任务,但我的解决方案不能正常工作。我有一个数组的对象“伴侣”,每个对象组成属性,姓名和年龄的每个伴侣(人)的任务是创建一个新的属性“朋友”,这应该包括伴侣的名字数组。
数组中的每个对象都有道具名称,所以道具朋友必须包含所有与自己的名称不同的对象名称。
我已经做了一个解决方案,但是朋友数组仍然包含所有的名称,包括当前对象的名称
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JS lessons6</title>
</head>
<!--<h1>Lesson 6</h1>-->
<body>
<!--<script src="mainForStudents.js"></script>-->
<script>
let mates = [
{name: 'john', age: 44},
{name: 'bob', age: 33},
{name: 'sam', age: 2},
]
let updatedMates = mates.map(el => (
{...el, friends: mates.map(el => el.name).filter(el => el !== el.name)}
))
console.log(updatedMates)
</script>
</body>
</html>
发布于 2021-07-30 06:43:47
您在任何地方都使用相同的el变量名。在查找变量时,最后一个filter()方法不必在最外层的map()中查找el,因为作用域中已经存在el。
您可以更改变量名来完成此操作:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JS lessons6</title>
</head>
<!--<h1>Lesson 6</h1>-->
<body>
<!--<script src="mainForStudents.js"></script>-->
<script>
let mates = [
{name: 'john', age: 44},
{name: 'bob', age: 33},
{name: 'sam', age: 2},
]
let updatedMates = mates.map(el => (
{...el, friends: mates.map(el1 => el1.name).filter(el2 => el2 !== el.name)}
))
console.log(updatedMates)
</script>
</body>
</html>
注意:并不需要将内部.map()中的变量名从el更改为el1。但我建议你这样做,这样你就可以避免将来出现这样的问题。
发布于 2021-07-30 06:47:45
请看内图和外图的变量。我看到了同样的"el“。正确的做法是:
let updatedMates = mates.map(el => (
{...el, friends: mates.map(el => el.name).filter(em => em !== el.name)}
))
https://stackoverflow.com/questions/68586467
复制相似问题