JavaScript中的+运算符和concat()方法有什么区别 [英] What is the difference of + operator and concat() method in JavaScript

查看:146
本文介绍了JavaScript中的+运算符和concat()方法有什么区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

加号(+)运算符 String.concat()方法会产生相同的结果。

The plus ( + ) operator and String.concat() method gives the same result.

加(+)运算符;

str1 + str2;

String concat()方法;

str1.concat(str2);

另外,它是用 w3schools ;


但是使用JavaScript,方法和属性也可用到
原始值,因为JavaScript在执行方法和属性时将原始值视为
对象。

But with JavaScript, methods and properties are also available to primitive values, because JavaScript treats primitive values as objects when executing methods and properties.

所以哪个方法最好用于组合我们在原语或JS中的String对象上使用它们,如果有的话,它们之间的性能优势和劣势是什么?

So which way is better to use to combine for either we use on primitives or on String objects in JS, what are the performance advantages and disadvantages between them if there is any?

var firstName = "John"      // String
var y = new String("John"); // with String Object

以下是给出相同结果的示例代码;

Here are the example codes which give same results;

function example1 () {
  var str1 = "Hello ";
  var str2 = "World!";
  document.getElementById("demo1").innerHTML += str1 + str2;
}


function example2 () {
  var str1 = "Hello ";
  var str2 = "World!";
  document.getElementById("demo2").innerHTML += str1.concat(str2);
}

function example3 () {
  var str1 = String("Hello ");
  var str2 = String("World!");
  document.getElementById("demo3").innerHTML += str1 + str2;
}

function example4 () {
  var str1 = String("Hello ");
  var str2 = String("World!");
  document.getElementById("demo4").innerHTML += str1.concat(str2);
}

example1();
example2();
example3();
example4();

<p id="demo1">Demo 1: </p>
<p id="demo2">Demo 2: </p>
<p id="demo3">Demo 3: </p>
<p id="demo4">Demo 4: </p>

推荐答案

有相同但 + 更清晰,更确定更快。

There are pretty the same but + is more clear and for sure faster.

看看此性能测试,另见 this


强烈建议赋值运算符使用(+,+ =)代替concat()方法。

It is strongly recommended that assignment operators (+, +=) are used instead of the concat() method.

这篇关于JavaScript中的+运算符和concat()方法有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆