Make writing a habit together! This is the third day of my participation in the “Gold Digging Day New Plan · April More text Challenge”. Click here for more details.

What do you think are the worst named apis in JS?

Hi, I’m LBJ. A few days ago, He talked about some of the worst named apis in JS. The list of winners includes:

Unshift, Splice, Substr, callee, and the alternatives sticky, stringify, and reduce

(Note the above ranking order)

In addition, others have added a simple summary as follows:

  1. I never knew what it wasarray.includesorcontains
  2. in,has,has-ownThose are too confusing
  3. for infor ofIt’s almost impossible to tell the difference to someone with a poor English foundation

In fact, it’s bad because the names are hard to understand and confusing. This article tries to solve this problem!

This article takes a look at 10 of these confusing apis in a nutshell

1. unshift

role

Unshift is used to add one or more elements to the beginning of an array and return the new length

The basic grammar

array.unshift(item1,item2, ... , itemX)Copy the code

For example,

let fruits = ["Apple"."Banana"];
let len = fruits.unshift("Lemon"."Orange");
console.log(len);/ / 4
console.log(fruits);//['Lemon', 'Orange', 'Apple', 'Banana']
Copy the code

Pay attention to

  • unshiftThe add element is added to the original array, sounshiftIt changes the original array

2. splice

role

Splice is used to intercept and add elements to an array. Add Add at the notch, add new data to the original array, return the truncated portion

The basic grammar

Array.splice (from the number of bits, the length of the cut, the data added at the cut1And the data2,...). ;Copy the code

The result will be different according to different parameters:

  • If nothing is passed, return an empty array [];
  • If the value is passed to the first value, it starts at that position and continues to the last bit of the array.
  • If the first and second parameters are passed, it indicates that the specified bits are intercepted from this position.
  • If additional arguments are passed, the subsequent arguments, starting with the third bit, are added to the notch as new members of the original group

For example,

let numbersArr = ['a'.'b'.'c'.1.2.3]
let strArr = numbersArr.splice(0.3)// Select 3 bits from 0 without adding new data
console.log(numbersArr);/ / [1, 2, 3]
console.log(strArr);// ['a', 'b', 'c']
Copy the code

Pay attention to

  • This method changes the original array unless nothing is passed, okay
  • In the new Chrome, an empty array is returned if nothing is passed. And older browsers, if they don’t pass anything, they might end up with the o’s starting, and they intercept the array.length-1 bit, which is equivalent to copying the array, right

3. substr

Many people confuse substr with substring because they do look very similar and are used to extract substrings (substrings)

role

The substr is used to extract a number of characters from the initial index number in the string

The substring is used to extract the characters between two specified index numbers in the string

grammar

string.substr(start,length)
Copy the code
  • The first argument, which represents the starting subscript to extract the substring
  • The second argument represents the length of the extracted string

For example,

let str = "Hello JueJin!"
let hello = str.substr(0.5)
console.log(hello) //Hello
console.log(str)//"Hello JueJin!"
Copy the code

Pay attention to

  • This method only extracts the string and does not alter the original string
  • If the second parameter is not passed, the last parameter is extracted

4. callee

Many people may confuse callee with caller. There seems to be only one letter difference between callee and Caller

role

Callee is the arguments object property, used to point to the function that owns the Arguments object. So when a function is called, its arguments.callee object points to itself, which is a reference to itself

Caller is a property of function that points to a function that calls the current function

grammar

function foo(){
    //xxx
    arguments.callee()
    //xxx
}
Copy the code

Calling arguments.callee() when the function executes is equivalent to recursively calling the function

For example,

Compute the levels of N

function mul(n){
    if(n==0||n==1) {return 1;
    }
    return n*arguments.callee(n-1);
}
Copy the code

Pay attention to

  • Arguments.callee is not supported in strict mode

5. sticky

Sticky is a regular expression object property that is read-only and cannot be enumerated

role

Its purpose is to reflect whether a search is sticky or not.

The value of sticky is Boolean and is true when the Y flag is used; Otherwise it is false

For example,

const str1 = 'Hello Juejin! ';
const regex1 = new RegExp('foo'.'y');
regex1.lastIndex = 6;// Specify the starting index for the next match

console.log(regex1.sticky);// true
console.log(regex1.test(str1));// true -- in this case, the match is successful only if lastIndex = 6, which is what sticky does
console.log(regex1.test(str1));// false
Copy the code

More reference

  • ECMA specification: ECMAScript (ECMA-262) RegExp. Prototype.sticky
  • MDN

6. stringify

role

Json.stringify () converts a JS object or value to a JSON-formatted string

grammar

JSON.stringify(value[, replacer [, space]])
Copy the code

Parameters:

  • Value: represents the JS object or value to be serialized into a JSON string

  • Replacer: Optional, used to process values to be serialized

If you specify a replacer function, you can optionally replace the value, or if the specified replacer is an array, you can optionally include only the properties specified by the array

  • space: Optional, specifies a blank string for indentation to beautify the output

The value of space can be one of the following:

  1. In the case of numbers, each level is indented more Spaces than the previous level, ranging from 1 to 10, that is, at least 1 and at most 10 Spaces.
  2. If it is a string, the string is appended to each line of serialization, and the string is indented at most one character at each level.
  3. If the value is null, undefined, or any other type, it is ignored and no action is taken

For example,

JSON.stringify(333) / / '333'
JSON.stringify(true) // 'true'
JSON.stringify(new String('333')) / / '" 333"
JSON.stringify(Boolean(true)) // 'true'

JSON.stringify('json') = = ='json' // false
JSON.stringify('json') = = ='"json"' // true

JSON.stringify(Symbol()) // undefined
JSON.stringify([Symbol(), Math.abs, undefined]) // '[null,null,null]'
JSON.stringify({ [Symbol()] :Math.abs, key: undefined }) / / '{}'

JSON.stringify(null) // 'null'
JSON.stringify(NaN) // 'null'

const obj = {}
Object.defineProperties(obj, {
  'json': { value: 'JSON'.enumerable: true },
  'stringify': { value: 'STRINGIFY'.enumerable: false}})JSON.stringify(obj)// '{"json":"JSON"}'

JSON.stringify({[Symbol()] :333}) / / '{}'

const a = { '1': 911.'r': 822.'11': 9922}
JSON.stringify(a)
// '{"1":911,"11":9922,"r":822}'

const a = { key: 'json' }
a.toJSON = () = > 'JSON'
JSON.stringify(a)// '"JSON"'

JSON.stringify(/\d/) / / "{}"
JSON.stringify(new Error())  / / "{}"

const a = {}
a.key = a
JSON.stringify(a)// Uncaught TypeError: Converting circular structure to JSON

JSON.stringify(12n)// Uncaught TypeError: Do not know how to serialize a BigInt

const a = {'\u0066': 333}
JSON.stringify(a)// '{"f":333}'

JSON.stringify(new Date())/ / '" thou T05:2022-04-14. 659 z "'
Copy the code

7. reduce

Why is Reduce here, as he says:

Add reduce is mainly because some comrades put forward that they don’t like this API, so they make up the number. Personally, I’m ok, because changing a name like fold isn’t much better.

Now that someone has mentioned it, let’s talk about it

role

The reduce method is used to perform a function you provide on each element of the array, summarizing the result into a single return value

grammar

array.reduce(callback(accumulator, currentValue[, index[, array]])[, initialValue])
Copy the code

Reduce accepts two parameters:

  • callbackfunction
  • initialValueThe initial value

Callback takes four arguments:

  1. accumulatorThe cumulative device
  2. current ValueThe current value
  3. indexThe current index
  4. arrayThe source array

For example,

/ / accumulation
[1.2.3.4.5.6.7.8].reduce((a, i) = > a + i);
// Output: 36

// add, default an initial value
[1.2.3.4.5.6.7.8].reduce((a, i) = > a + i, 5);
// Output: 41

/ / multiplicative
[1.2.3.4.5.6.7.8].reduce((a, i) = > a * i);
// Output: 40320
Copy the code

8. array.includes

Some say it’s always confusing whether it’s array.includes or array.contains because both words are common

In fact, arrays do not contain methods, only includes methods

He Lao’s explanation is:

Originally called contains, but due to compatibility problems had to be changed to include

role

Includes is used to determine whether an array contains an element. Contains return true and non-contains return false. This is similar to the includes method of strings

grammar

arr.includes(searchElement)
arr.includes(searchElement, fromIndex)
Copy the code
  • The first parameter indicates the element to look for
  • The second parameter indicates the starting position of the search

For example,

let arr = [1.2.3]
let res = arr.includes(1)
console.log(res)//true
Copy the code

Pay attention to

  • If the second argument is negative, it is searched backwards from the penultimate digit

9. in,hasandhas-own

These three are completely different things:

  • So let’s first look at in

It is often used in two situations

The first is the for in loop. For in is used to iterate over any object, including arrays, but by default keys are iterated over, for example:

let list = [1.2.3];
for (let i in list) {
    console.log(i); 
}
Copy the code

In the above code, use for… In iterates over the index of the array “0”, “1”, “2”

Another case is the variable in object

Is used to check if the preceding object is a property of the following object (even if it is in the prototype).

  • Let’s move on to has

Common cases, such as map.prototype.has ()

It is used to indicate whether the specified element exists in the map, for example:

var myMap = new Map(a); myMap.set("bar"."foo");

myMap.has("bar");  // true
myMap.has("baz");  //false
Copy the code
  • Finally,has-own

Such as the Object. The prototype. HasOwnProperty (), used to detect whether a property belongs to an Object, and the difference is that in hasOwnProperty ruled out on the prototype

const object1 = {};
object1.property1 = 42;

console.log(object1.hasOwnProperty('property1'));// true
console.log(object1.hasOwnProperty('toString'));//false
console.log(object1.hasOwnProperty('hasOwnProperty'));// false
Copy the code

10. For in and for of

for.. Of and the for… In is both used for iteration, but they are different

The first is that the values of the iterations differ

for.. In iterates over the list of the object’s keys, while for.. Of iterates over the value of the key of the object

For example 1

let list = [1.2.3];
for (let i in list) {
    console.log(i); 
}
for (let i of list) {
    console.log(i); 
}
Copy the code

In the above code, use for… In iterates over the array’s subscripts “0”, “1”, “2”, instead of using for.. The value of “1”, “2”, “3”

Another major difference is that for in can operate on any object; It provides a way to view the properties of an object.

But for of focuses on the value of the iterated object. The built-in Map and Set objects already implement symbol. iterator methods that give us access to the values they hold.

For example 2

let pets = new Set(["Cat"."Dog"]);
pets["species"] = "mammals";

for (let pet in pets) {
    console.log(pet); // "species"
}

for (let pet of pets) {
    console.log(pet); // "Cat", "Dog"
}
Copy the code

conclusion

That is all the content of this article, if you have any questions, please correct 🌹