gpt4 book ai didi

javascript - 如果在 JavaScript 中的 if 条件之后使用两个等号而不是仅一个等号,会发生什么情况?

转载 作者:行者123 更新时间:2023-11-28 15:12:08 25 4
gpt4 key购买 nike

我仍在学习,所以如果我的问题格式不正确,我很抱歉。

我试图编写一个函数来将一个单词插入到字符串的指定位置,但是我犯了一个错误,在执行 block 中写了两个等号==而不是一个,并且这导致测试时输出错误。

但是,我已经知道 if/else 之后的代码执行不需要是 bool 值,我注意到了这个拼写错误,并通过删除一个等号来纠正它该函数工作得很好,但我只是想知道为什么我从来没有质疑过在 if 条件之后执行代码时严格使用一个等号的重要性。

所以这是错误的代码:

function insert(original,to_insert,position){ 
if (to_insert == "undefined" && position == undefined){return original;}
else if (position == undefined){position == 0}

var x = original.slice(0,position);

var y = original.slice(position);

console.log(x + to_insert + y);
}

insert('We are doing some exercises.','JavaScript ');
//Wrong output >>>> "We are doing some exercises.JavaScript We are doing some exercises."

insert('We are doing some exercises.','JavaScript ', 18);
//correct output>>>> "We are doing some JavaScript exercises."

这是正确的代码:

function insert(original,to_insert,position){ 
if (to_insert == "undefined" && position == undefined){return original;}
else if (position == undefined){position = 0}

var x = original.slice(0,position);

var y = original.slice(position);

console.log(x + to_insert + y);
}

insert('We are doing some exercises.','JavaScript ');
//correct output >>>> JavaScript We are doing some exercises."

insert('We are doing some exercises.','JavaScript ', 18);
//correct output>>>> "We are doing some JavaScript exercises."

请您解释一下我的错误代码中发生了什么,例如使用 bool 值时导致函数无法正常运行的原因,显然该函数一次运行一次,那么位置的绝对值与位置的绝对值相比会有什么区别位置的可变值。

提前致谢

最佳答案

else if (position == undefined){position == 0}

在你的错误代码中,position仍然是undefined,因为你没有进行赋值,你只需检查position是否(这是 >未定义)等于0

因此,当您执行 var x = original.slice(0,position); slice() 时,只需忽略第二个参数,在本例中为 未定义并从开始到结束进行切片,这是不使用第二个参数时的默认行为。

来自MDN :

The slice() method extracts a section of a string and returns a new string.

str.slice(beginSlice[, endSlice])

endSlice

Optional. The zero-based index at which to end extraction. If omitted, slice() extracts to the end of the string. If negative, it is treated as sourceLength + endSlice where sourceLength is the length of the string (for example, if endSlice is -3 it is treated as sourceLength - 3).

就您而言,由于您传递了 undefined (因为 position == undefined),所以就像您省略了它

关于javascript - 如果在 JavaScript 中的 if 条件之后使用两个等号而不是仅一个等号,会发生什么情况?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35963759/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com