Javascript String Assignment Operators

后端 未结 6 549
执笔经年
执笔经年 2021-01-17 17:12

How come I can use += on a string, but I cannot use -= on it?

For example...

var test = \"Test\";
var arr = \"⇔\"         


        
6条回答
  •  南方客
    南方客 (楼主)
    2021-01-17 17:13

    As all said, the -= operator is not overloaded to work with Strings, it only works with Numbers.

    If you try to use it with strings, the operator will try to convert both operands to Number, that is why you are getting NaN, because:

    isNaN(+"foo"); // true
    

    To get rid of the arr content on your test string, you can replace it:

    var test = "Test",
        arr = "⇔"
    
    test += arr;
    alert(test);  // Shows "Test⇔"
    
    test = test.replace(arr, ""); // replace the content of 'arr' with "" on 'test'
    alert(test);  // Shows "Test"
    

提交回复
热议问题