您应该知道的一些 Javascript 方法
在本文中,我们将介绍一些你应该了解的 JavaScript 方法。如果你也了解一些,那么可以直接跳过本节。那就让我们开始吧。
连接(..)
此方法可用于数组以及字符串。如果两个变量或部分属于同一数据类型,则将他们连接在一起。
let a = "foo";
let b = ["f", "o", "o"];
let c = a.concat("bar"); // "foobar"
let d = b.concat(["b", "a", "r"]); // ["f","o","o","b","a","r"]
因为它不会改变实际变量,所以我们总是需要存储返回的值,concat
例如 -
console.log(a); // "foo"
console.log(b); // [ 'f', 'o', 'o' ]
console.log(c); // "foobar"
console.log(d); // [ 'f', 'o', 'o', 'b', 'a', 'r' ]
撤销()
数组具有reverse()
就地 mutator 方法,但字符串没有,所以我们只能在数组中使用它,而不能在字符串中使用它。
let a = "foo";
let b = ["f", "o", "o", "!"];
a.reverse; // undefined
b.reverse(); // ["!","o","O","f"]
console.log(b); // ["!","o","O","f"]
由于此方法无法反转字符串,那么问题是如何反转字符串?答案很简单,我们必须为此创建一个函数。
let a = "foo";
// function for reversing a string
function reverseString(str) {
return str.split("").reverse().join("");
}
console.log(a); // "foo"
let b = reverseString(a);
console.log(b); // "oof"
reverseString()
方法返回值,所以我们需要将其存储在变量中,这样它就能正常工作了。在上面的例子中,我们只是将一个字符串拆分成一个数组,然后使用reverse()
and将其join()
合并在一起。
分裂(..)
在上一节中我们使用了该split()
方法,现在让我们看看它实际上是如何工作的。
let a = "foo";
let arr = a.split("");
console.log(a); // foo
console.log(arr); // [ 'f', 'o', 'o' ]
split()
方法返回一个数组,并根据传入的参数进行拆分。例如:
加入(..)
在前面的例子中,我们join()
也使用了它将数组转换为字符串。
let a = ["f", "o", "o", "!"];
let str = a.join("");
console.log(a); // [ 'f', 'o', 'o', '!' ]
console.log(str); // foo!
到指数()
该方法将值转换为指数,正如其名称所示。让我们看看如何实现它。
let a = 5e7;
console.log(a); // 50000000
let b = a.toExponential();
console.log(b); // 5e+7
现在,如果我们在其中使用一些数学运算会怎样?让我们看看。
var c = b * b;
console.log(c); // 2.5e+21
var d = 1 / b;
console.log(d); // 2e-11
固定(..)
toFixed(..)
方法允许您指定要用多少
位小数来表示该值:
let a = 42.59;
a.toFixed(0); // "43"
a.toFixed(1); // "42.6"
a.toFixed(2); // "42.59"
a.toFixed(3); // "42.590"
a.toFixed(4); // "42.5900"
到精度(..)
toPrecision(..)
类似,但指定应使用多少位有效数字来表示该值:
var a = 42.59;
a.toPrecision(1); // "4e+1"
a.toPrecision(2); // "43"
a.toPrecision(3); // "42.6"
a.toPrecision(4); // "42.59"
a.toPrecision(5); // "42.590"
其他例子 -
42.toFixed( 3 ); // SyntaxError
// these are all valid:
(42).toFixed( 3 ); // "42.000"
0.42.toFixed( 3 ); // "0.420"
42..toFixed( 3 ); // "42.000"
42.toFixed(3)
是无效语法,因为 . 被吞噬为42
. 文字的一部分(这是有效的 - 参见上文!),因此不存在 . 属性运算符来进行访问.toFixed
。
42..toFixed(3)
之所以有效,是因为第一个.
是数字的一部分,第二个.
是属性运算符。但这看起来可能很奇怪,而且在实际的 JavaScript 代码中,这种做法确实很少见。
结论
还有很多方法我还没讲到,比如,,length
等等。也许以后我们会讲到这些。想看这类文章,可以考虑关注我。indexOf
toUpperCase
另请阅读 -
将 Next.js 应用转换为 PWA
每个人都应该知道的 10 个 Git 命令