首页 > 解决方案 > 下面的代码将向控制台输出什么,为什么?

问题描述

我正在将输出输出到下面的代码,但我不知道它是如何工作的,谁能告诉我输出的原因是什么。

console.log(1 + "2" + "2");
console.log(1 + +"2" + "2");
console.log(1 + -"1" + "2");
console.log(+"1" + "1" + "2");
console.log("A" - "B" + "2");
console.log("A" - "B" + "2");

标签: javascriptoperators

解决方案


console.log(1 + "2" + "2"); // it is concat as string
console.log(1 + +"3" + "2"); // 2nd + makes 2 as string to integer. but second 2 is string. so it makes 42
console.log(1 + -"1" + "2");// 2nd - makes 1 as string to integer. but second 2 is string. so it makes 02
console.log(+"1" + "1" + "2");// 1st - makes 1 as string to integer. and same behaviour of the first logging
console.log("A" - "B" + "2"); // - cannot used for string values. nor this reason find A - B is NAN and adding 2 as string.
//console.log("A" - "B" + "2); // syntax eerror. second " in 2 missing


推荐阅读