前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【前端】:JS 内置对象必知必会

【前端】:JS 内置对象必知必会

作者头像
WEBJ2EE
发布2020-02-26 09:52:23
8550
发布2020-02-26 09:52:23
举报
文章被收录于专栏:WebJ2EEWebJ2EE
代码语言:javascript
复制
目录
1. Number
   1.1. 是什么?
   1.2. 常用方法
     1.2.1. toFixed()
     1.2.2. toPrecision()
     1.2.3. toExponential()
2. Math
    2.1. Math.round()
3. Array
    3.1. shift()    
    3.2. unshift()
    3.3. forEach()
    3.4. splice()
    3.5. reduce()
    3.6. concat()
    3.7. slice()
4. Object
    4.1. assign()
    4.2. keys()
5. 几道笔试题

1. Number

1.1. 是什么?

根据 ECMAScript 标准,JavaScript 中只有一种数字类型:基于 IEEE 754 标准的双精度 64 位二进制格式的值(-(2^53 -1) 到 2^53 -1)。它并没有为整数给出一种特定的类型。除了能够表示浮点数外,还有一些带符号的值:+Infinity,-Infinity 和 NaN (非数值,Not-a-Number)。

1.2. 常用方法

1.2.1. toFixed()

toFixed() 方法使用定点表示法来格式化一个数值。

示例:

代码语言:javascript
复制
var numObj = 12345.6789;
numObj.toFixed();         // 返回 "12346":进行四舍五入,不包括小数部分
numObj.toFixed(1);        // 返回 "12345.7":进行四舍五入
numObj.toFixed(6);        // 返回 "12345.678900":用0填充
(1.23e+20).toFixed(2);    // 返回 "123000000000000000000.00"
(1.23e-10).toFixed(2);    // 返回 "0.00"
2.34.toFixed(1);          // 返回 "2.3"
-2.34.toFixed(1);         // 返回 -2.3 (由于操作符优先级,负数不会返回字符串)
(-2.34).toFixed(1);       // 返回 "-2.3" (若用括号提高优先级,则返回字符串)

1.2.2. toPrecision()

toPrecision() 方法以指定的精度返回该数值对象的字符串表示。

示例:

代码语言:javascript
复制
var numObj = 5.123456;
console.log("numObj.toPrecision()  is " + numObj.toPrecision());  //输出 5.123456
console.log("numObj.toPrecision(5) is " + numObj.toPrecision(5)); //输出 5.1235
console.log("numObj.toPrecision(2) is " + numObj.toPrecision(2)); //输出 5.1
console.log("numObj.toPrecision(1) is " + numObj.toPrecision(1)); //输出 5

// 注意:在某些情况下会以指数表示法返回
console.log((1234.5).toPrecision(2)); // "1.2e+3"

1.2.3. toExponential()

toExponential() 方法以指数表示法返回该数值字符串表示形式。

示例:

代码语言:javascript
复制
var numObj = 77.1234;

alert("numObj.toExponential() is " + numObj.toExponential()); //输出 7.71234e+1

alert("numObj.toExponential(4) is " + numObj.toExponential(4)); //输出 7.7123e+1

alert("numObj.toExponential(2) is " + numObj.toExponential(2)); //输出 7.71e+1

alert("77.1234.toExponential() is " + 77.1234.toExponential()); //输出 7.71234e+1

alert("77 .toExponential() is " + 77 .toExponential()); //输出 7.7e+1

2. Math

2.1. Math.round()

Math.round() 函数返回一个数字四舍五入后最接近的整数。

示例:

代码语言:javascript
复制
Math.round( 20.49); //  20
Math.round( 20.5 ); //  21
Math.round( 42   ); //  42
Math.round(-20.5 ); // -20
Math.round(-20.51); // -21

3. Array

3.1. shift()

The shift() method removes the first element from an array and returns that removed element. This method changes the length of the array.

3.2. unshift()

The unshift() method adds one or more elements to the beginning of an array and returns the new length of the array.

Please note that, if multiple elements are passed as parameters, they're inserted in chunk at the beginning of the object, in the exact same order they were passed as parameters. Hence, calling unshift with n arguments once, or calling it n times with 1 argument (with a loop, for example), don't yield the same results.

示例:

代码语言:javascript
复制
let arr = [4, 5, 6]

arr.unshift(1, 2, 3)
console.log(arr);
// [1, 2, 3, 4, 5, 6]

arr = [4, 5, 6] // resetting the array

arr.unshift(1)
arr.unshift(2)
arr.unshift(3)

console.log(arr)
// [3, 2, 1, 4, 5, 6]

3.3. forEach()

The forEach() method executes a provided function once for each array element.

  • It is not invoked for index properties that have been deleted or are uninitialized.
  • The range of elements processed by forEach() is set before the first invocation of callback. Elements which are appended to the array after the call to forEach() begins will not be visited by callback.
  • If existing elements of the array are changed or deleted, their value as passed to callback will be the value at the time forEach() visits them;
  • elements that are deleted before being visited are not visited.
  • If elements that are already visited are removed (e.g. using shift()) during the iteration, later elements will be skipped.
  • There is no way to stop or break a forEach() loop other than by throwing an exception.

示例1:No operation for uninitialized values (sparse arrays)

代码语言:javascript
复制
const arraySparse = [1,3,,7]
let numCallbackRuns = 0
arraySparse.forEach(function(element){
  console.log(element)
  numCallbackRuns++
})

console.log("numCallbackRuns: ", numCallbackRuns)

// 1
// 3
// 7
// numCallbackRuns: 3
// comment: as you can see the missing value between 3 and 7 didn't invoke callback function.

示例2:If the array is modified during iteration, other elements might be skipped

代码语言:javascript
复制
let words = ['one', 'two', 'three', 'four']
words.forEach(function(word) {
  console.log(word)
  if (word === 'two') {
    words.shift()
  }
})
// one
// two
// four

3.4. splice()

The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place.

示例1:Remove 0 (zero) elements from index 2, and insert "drum"

代码语言:javascript
复制
let myFish = ['angel', 'clown', 'mandarin', 'sturgeon']
let removed = myFish.splice(2, 0, 'drum')

// myFish is ["angel", "clown", "drum", "mandarin", "sturgeon"] 
// removed is [], no elements removed

示例2:Remove 1 element from index 3

代码语言:javascript
复制
let myFish = ['angel', 'clown', 'drum', 'mandarin', 'sturgeon']
let removed = myFish.splice(3, 1)

// removed is ["mandarin"]
// myFish is ["angel", "clown", "drum", "sturgeon"]

示例3:Remove 1 element from index 2, and insert "trumpet"

代码语言:javascript
复制
let myFish = ['angel', 'clown', 'drum', 'sturgeon']
let removed = myFish.splice(2, 1, 'trumpet')

// myFish is ["angel", "clown", "trumpet", "sturgeon"]
// removed is ["drum"]

示例4:Remove 1 element from index -2

代码语言:javascript
复制
let myFish = ['angel', 'clown', 'mandarin', 'sturgeon']
let removed = myFish.splice(-2, 1)

// myFish is ["angel", "clown", "sturgeon"] 
// removed is ["mandarin"]

示例:Remove all elements after index 2 (incl.)

代码语言:javascript
复制
let myFish = ['angel', 'clown', 'mandarin', 'sturgeon']
let removed = myFish.splice(2)

// myFish is ["angel", "clown"]
// removed is ["mandarin", "sturgeon"]

3.5. reduce()

The reduce() method executes a reducer function (that you provide) on each element of the array, resulting in a single output value.

示例:

代码语言:javascript
复制
[0, 1, 2, 3, 4].reduce(function(accumulator, currentValue, currentIndex, array) {
  return accumulator + currentValue
})

3.6. concat()

The concat() method is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array.

  • The concat method creates a new array consisting of the elements in the object on which it is called, followed in order by, for each argument, the elements of that argument (if the argument is an array) or the argument itself (if the argument is not an array). It does not recurse into nested array arguments.

示例1:Concatenating two arrays

代码语言:javascript
复制
const letters = ['a', 'b', 'c'];
const numbers = [1, 2, 3];

letters.concat(numbers);
// result in ['a', 'b', 'c', 1, 2, 3]

示例2:Concatenating nested arrays

代码语言:javascript
复制
const num1 = [[1]];
const num2 = [2, [3]];

const numbers = num1.concat(num2);

console.log(numbers);
// results in [[1], 2, [3]]

// modify the first element of num1
num1[0].push(4);

console.log(numbers);
// results in [[1, 4], 2, [3]]

3.7. slice()

The slice() method returns a shallow copy of a portion of an array into a new array object selected from begin to end (end not included) where begin and end represent the index of items in that array. The original array will not be modified.

示例1:Return a portion of an existing array

代码语言:javascript
复制
let fruits = ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango']
let citrus = fruits.slice(1, 3)

// fruits contains ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango']
// citrus contains ['Orange','Lemon']

4. Object

4.1. assign()

The Object.assign() method copies all enumerable own properties from one or more source objects to a target object. It returns the target object.

  • Properties in the target object are overwritten by properties in the sources if they have the same key. Later sources' properties overwrite earlier ones.

示例:

代码语言:javascript
复制
const o1 = { a: 1 };
const o2 = { b: 2 };
const o3 = { c: 3 };

const obj = Object.assign(o1, o2, o3);
console.log(obj); // { a: 1, b: 2, c: 3 }
console.log(o1);  // { a: 1, b: 2, c: 3 }, target object itself is changed.

4.2. keys()

The Object.keys() method returns an array of a given object's own enumerable property names, iterated in the same order that a normal loop would.

示例:

代码语言:javascript
复制
// simple array
const arr = ['a', 'b', 'c'];
console.log(Object.keys(arr)); // console: ['0', '1', '2']

// array like object
const obj = { 0: 'a', 1: 'b', 2: 'c' };
console.log(Object.keys(obj)); // console: ['0', '1', '2']

// array like object with random key ordering
const anObj = { 100: 'a', 2: 'b', 7: 'c' };
console.log(Object.keys(anObj)); // console: ['2', '7', '100']

// getFoo is a property which isn't enumerable
const myObj = Object.create({}, {
  getFoo: {
    value: function () { return this.foo; }
  } 
});
myObj.foo = 1;
console.log(Object.keys(myObj)); // console: ['foo']

5. 几道笔试题

题目01:

题目02:

题目03:

题目04:

题目05:

题目06:

题目07:

题目08:

参考:

《Javascript权威指南》 Determining with absolute accuracy whether or not a JavaScript object is an array: http://web.mit.edu/jwalden/www/isArray.html 术语表:Number https://developer.mozilla.org/zh-CN/docs/Glossary/Number

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2020-02-18,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 WebJ2EE 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档