2024年Web前端最全【面试题】在循环 for、for-in、forEach、for-of (2),2024年最新2024-2024历年网易跳动Web前端面试真题解析

读者福利

========

开源分享:【大厂前端面试题解析+核心总结学习笔记+真实项目实战+最新讲解视频】

由于篇幅过长,就不展示所有面试题了,想要完整面试题目的朋友(另有小编自己整理的2024大厂高频面试题及答案附赠)


for

改变item本身

由于for 循环里,没有专门的一个变量"item",可以获取到对应的引用,我们只能用list[index]的形式去获取到每一项。

我们运行看看效果。

const list = [
  {name: 'a', count: 1},
  2,
  function fn() {
    console.log(3);
  },
  [4,4,4,4],
  new Date()
]

for (let i = 0; i < list.length; i ++) {
  list[i] = 4
}

console.log(list)

复制代码
[ 4, 4, 4, 4, 4 ]

复制代码

全部被无差别覆盖了。

改变item的属性

const list = [
  {name: 'a', count: 1},
  2,
  function fn() {
    console.log(3);
  },
  [4,4,4,4],
  new Date()
]

for (let i = 0; i < list.length; i ++) {
  list[i].count = 4
}

console.log(list)

复制代码
[
  { name: 'a', count: 4 },
  2,
  [Function: fn] { count: 4 },
  [ 4, 4, 4, 4, count: 4 ],
  2022-09-13T10:44:50.164Z { count: 4 }
]
复制代码

我们发现,和forEach的时候,表现一致:

  • 基础类型的,依旧没有发生改变。
  • 引用类型的变量,如果自身带了count属性,该属性就会被修改;如果不带该属性,就会添加count属性。

for-in

const list = [
  {name: 'a', count: 1},
  2,
  function fn() {
    console.log(3);
  },
  [4,4,4,4],
  new Date()
]

for(let i in list) {
  list[i] = 4
}

console.log(list)

复制代码
[ 4, 4, 4, 4, 4 ]
复制代码

for in 其实和for循环一致,因为他们都是取到了index,然后修改list[index]

这里就不分别看改变item和改变item属性了。

for of

改变item本身

const list = [
  {name: 'a', count: 1},
  2,
  function fn() {
    console.log(3);
  },
  [4,4,4,4],
  new Date()
]

for(let i of list) {
  i = 4
}

console.log(list)

复制代码

[
  { name: 'a', count: 1 },
  2,
  [Function: fn],
  [ 4, 4, 4, 4 ],
  2022-09-13T10:56:11.711Z
]

复制代码

我们发现item无法别更改。

改变item的属性

const list = [
  {name: 'a', count: 1},
  2,
  function fn() {
    console.log(3);
  },
  [4,4,4,4],
  new Date()
]

for(let i of list) {
  i.count = 4
}

console.log(list)

复制代码

[
  { name: 'a', count: 4 },
  2,
  [Function: fn] { count: 4 },
  [ 4, 4, 4, 4, count: 4 ],
  2022-09-13T10:57:36.085Z { count: 4 }
]

复制代码

我们发现:结果和forEach一致。他们都是在迭代函数里拿到了item。

map

改变item本身

const list = [
  {name: 'a', count: 1},
  2,
  function fn() {
    console.log(3);
  },
  Symbol(),
  [4,4,4,4],
  new Date()
]

list.map(item => {
  item = 4
})

console.log(list)

复制代码
[
  { name: 'a', count: 1 },
  2,
  [Function: fn],
  Symbol(),
  [ 4, 4, 4, 4 ],
  2022-09-13T11:01:10.614Z
]

复制代码

我们发现,item无动于衷。

改变item的属性

const list = [
  {name: 'a', count: 1},
  2,
  function fn() {
    console.log(3);
  },
  Symbol(),
  [4,4,4,4],
  new Date()
]

list.map(item => {
  item.count = 4
})

console.log(list)
复制代码
[
  { name: 'a', count: 4 },
  2,
  [Function: fn] { count: 4 },
  Symbol(),
  [ 4, 4, 4, 4, count: 4 ],
  2022-09-13T10:59:53.050Z { count: 4 }
]
复制代码

分析总结

读者福利

========

开源分享:【大厂前端面试题解析+核心总结学习笔记+真实项目实战+最新讲解视频】

由于篇幅过长,就不展示所有面试题了,想要完整面试题目的朋友(另有小编自己整理的2024大厂高频面试题及答案附赠)


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值