这只是因为JavaScript是一种基于原型的编程语言。
原型编程被认为鼓励程序员专注于一些示例的行为,只有在后期才会担心将这些对象分类为原型对象,然后以类似于类的方式使用它们。 因此,许多基于原型的系统鼓励在运行时更改原型。
这意味着你可以做这样的事情:
var str = 'foo'
str.weight // just return 'undefined'
var yes = true, no = false
yes.__proto__.length = function() { return this.toString().length; }
yes.length() // 4
no.length() // 5
var num = 10, amount = 0
num.__proto__.plus = function(num) { return this + num; }
amount.plus(num) // 10
但不幸的是,JavaScript 的一些特性受到了 Java 的影响,例如原始值与对象之间的区别,因此你会遇到这些奇怪的问题:
var str = 'foo'
str.weight = 42
str.weight // undefined
str = new String('foo')
str.weight = 42
str.weight // 42
1.toString() // error!
var n = 1
n.toString() // '1'
var str = 'hello user #',
num = 3,
sayhello = str + num;
alert(sayhello); // alerts 'hello user #3'
parseInt
方法:var returnWholeNumber = function (arg) {
return parseInt(arg, 10);
},
str = '5 is the answer',
num = 8.19437;
alert(returnWholeNumber(str)); // alerts number 5
alert(returnWholeNumber(num)); // alerts number 8
0
或空字符串 ''
)被称为“falsey”。这样,您可以对它们进行简单的布尔检查,JavaScript 将原始数据类型包装在 Boolean 包装器中。if (!userInput) {
alert('no input');
}
alert('1' + 2 + 3); // alerts 123
alert('1' + '2' + '3'); // alerts 123
alert(1 + 2 + 3); // alerts 6
对于条件语句,也要使用三个等号来检查类型,以避免意外的强制转换:
var i = '3';
if (i == 3) { // type-coercing conditional; i can be a string or a number and this will be true
alert('i is 3'); // will successfully alert
}
if (i === 3) { // type-checking conditional; i has to be an actual number (and the value must be 3)
alert('i is a number 3'); // will not alert because i is a string
}
var string =“somestring”;string = 1234; //不会抛出错误
- Paul S.