• Native Methods You May Not Know
  • Original text: Moon
  • The Nuggets translation Project
  • Permanent link to this article: github.com/xitu/gold-m…
  • Translator: Jessica
  • Proofreader: Baddyo, Chorer

Native JavaScript methods you may not know about

Some powerful but often overlooked native JavaScript methods

Since the release of ES6, many new and convenient native methods have been added to the new standard for JavaScript.

However, I still see a lot of old code in the GitHub repository. This is not to say that they are bad, of course, but that the code is much more readable and aesthetically pleasing if you use the features I describe below.


Number. The isNaN isNaN contrast

NaN is of type number.

typeof NaN= = ='number'
Copy the code

So you can’t directly distinguish NaN from ordinary numbers.

Even for NaN and ordinary Numbers, when the Object. The prototype. ToString. When the call method will return [Object Number]. You probably already know that the isNaN method can be used to check if the parameter isNaN. But since ES6, the constructor Number() has also started using isNaN as its method. So, what’s the difference?

  • isNaNCheck whether the value is not a normal number or cannot be converted to a normal number.
  • Number.isNaN— Check if the value is NaN.

Here are some examples. Folks on Stack Overflow have already discussed this topic.

Number.isNaN({});
// < -false, {} is not NaN
Number.isNaN('ponyfoo')
// < -false, 'ponyfoo' is not a NaN
Number.isNaN(NaN)
// < -true, NaN is NaN
Number.isNaN('pony'/'foo')
// < -true, 'pony'/'foo' is NaN, NaN is NaN

isNaN({});
// < -true, {} is not an ordinary number
isNaN('ponyfoo')
// < -true, 'ponyfoo' is not an ordinary number
isNaN(NaN)
// < -true, NaN is not an ordinary number
isNaN('pony'/'foo')
// < -true, 'pony'/'foo' is NaN, NaN is not a common number
Copy the code

Number. IsFinite isFinite contrast

In JavaScript, a calculation like 1/0 does not produce an error. Instead, it returns an attribute of the global object, Infinity.

So, how do you check if a value is infinite? Sorry, you can’t do that. However, you can use isFinite and number.isfinite to check if the value isFinite.

They work basically the same way, but are slightly different from each other.

  • isFiniteCheck if the value passed in is finite. If the type of the value passed is notnumberType that attempts to convert this value tonumberType, and then judge.
  • Number.isFiniteCheck if the value passed in is finite. Even if the type of the value passed is notnumberType, also does not attempt to convert, but to judge directly.
Number.isFinite(Infinity) // false
isFinite(Infinity) // false

Number.isFinite(NaN) // false
isFinite(NaN) // false

Number.isFinite(2e64) // true
isFinite(2e64) // true

Number.isFinite(undefined) // false
isFinite(undefined) // false

Number.isFinite(null) // false
isFinite(null) // true

Number.isFinite('0') // false
isFinite('0') // true
Copy the code

Math. Math floor contrast. Trunc

In the past, you might have used the math.floor function when you needed to extract the number to the right of the decimal point. But from now on, if all you really want is the integer part, try the math.trunc function.

  • Math.floor— Returns the largest integer less than or equal to the given number.
  • Math.truncReturns the integer part of the number.

Basically, if a given number is positive, they give exactly the same result. But if the given number is negative, the result is different.

Math.floor(1.23) / / 1
Math.trunc(1.23) / / 1

Math.floor(5.3) / / - 6
Math.trunc(5.3) / / - 5

Math.floor(0.1) // -1
Math.trunc(0.1) / / - 0
Copy the code

Array. The prototype. IndexOf contrast Array. Prototype. Includes

When you want to find a value in a given array, how do you find it? I have seen many developers use array.prototype.indexof, as shown in the following example.

const arr = [1.2.3.4];

if (arr.indexOf(1) > - 1) {... }Copy the code
  • Array.prototype.indexOf— Returns the first index of the given element that can be found in the array, or if none exists- 1.
  • Array.prototype.includesCheck if the given array contains the specific value to look for, and returntrue/falseAs a result.
const students = ['Hong'.'James'.'Mark'.'James'];

students.indexOf('Mark') / / 1
students.includes('James') // true

students.indexOf('Sam') // -1
students.includes('Sam') // false
Copy the code

Note that the values passed in are case sensitive due to Unicode encoding differences.


String.prototype.repeat contrast for loop

Before this feature was added to ES6, the way to generate strings like abcabcabc was to copy the string as many times as you needed and concatenate it to an empty string.

var str = 'abc';
var res = ' ';

var copyTimes = 3;

for (var i = 0; i < copyTimes; i += 1) {
  for (var j = 0; j < str.length; j += 1) { res += str[j]; }}Copy the code

But this realism is long, messy and sometimes unreadable. To do this, we can use the string.prototype. repeat function. All you need to do is pass in a number that indicates how many times you want to repeat the string.

'abc'.repeat(3) // "abcabcabc"
'hi '.repeat(2) // "hi hi "

'empty'.repeat(0) / / ""
'empty'.repeat(null) / / ""
'empty'.repeat(undefined) / / ""
'empty'.repeat(NaN) / / ""

'error'.repeat(- 1) // RangeError
'error'.repeat(Infinity) // RangeError
Copy the code

The value passed in cannot be negative, must be less than infinity, and cannot exceed the maximum length of the string, which would cause an overflow.


String. The prototype. Contrast match String. Prototype. Includes

There are two methods to check whether a particular string is contained in a string — the match function and the includes function.

  • String.prototype.match— Accepts arguments of type RegExp. All flags supported in RegExp are available.
  • String.prototype.includes— Accepts two arguments, the first of which issearchStringThe second argument isposition. If it doesn’t come inpositionParameter, the default value is used0.

The difference is that includes is case sensitive, while match is not. You can place the tag I in RegExp to make it case insensitive.

const name = 'jane';
const nameReg = /jane/i;

const str = 'Jane is a student';

str.includes(name) // false
str.match(nameReg) 
// ["Jane", index: 0, input: "Jane is a student", groups: undefined]
Copy the code

String. The prototype. String concat contrast. Prototype. PadStart

PadStart is a useful method when you want to add strings to the beginning of a string.

Similarly, the concat function can do the job just fine. But the main difference is that the padStart function repeatedly populates the string from the argument into the result string, starting with the first digit of the result string.

I’ll show you how to use this function.

const rep = 'abc';
const str = 'xyz';
Copy the code

There are two strings here. I want to add rep before XYZ — but instead of just adding it once, I want to add it repeatedly.

str.padStart(10, rep);
Copy the code

PadStart takes two arguments — the total length of the newly created result string and the string to be repeated. The easiest way to understand this function is to write it down with Spaces instead of letters.

1) _ _ _ _ _ _ _ _ _ _ // In the space'xyz'Fill in 2) _ _ _ _ _ _ _ x y z // Repeat in the remaining blanks'abc'/ / until'xyz'3) ab C ab C a X y Z // The result will eventually be 4) abcabcaxyzCopy the code

This function is very useful for this particular scenario, and is absolutely difficult to do with concat (a function that also performs string applets).

The padEnd function is the same as the padStart function, except that it starts at the end of the position.


conclusion

There are many interesting and useful methods in JavaScript. Just because they’re not common doesn’t mean they’re useless. It’s up to you to use them wisely.

The resources

  • Confusion between isNaN functions and number. isNaN functions in JavaScript
  • Number.isFinite —— MDN
  • IsFinite – MDN
  • Math. Trunc — — MDN
  • Math. Floor — — MDN
  • Array. The prototype. IndexOf – MDN
  • Array. The prototype. Includes – MDN
  • String. The prototype. Repeat – the MDN
  • String. The prototype. The math – MDN
  • String. The prototype. Includes – MDN
  • String. The prototype. PadStart – MDN

If you find any mistakes in your translation or other areas that need to be improved, you are welcome to the Nuggets Translation Program to revise and PR your translation, and you can also get the corresponding reward points. The permanent link to this article at the beginning of this article is the MarkDown link to this article on GitHub.


The Nuggets Translation Project is a community that translates quality Internet technical articles from English sharing articles on nuggets. The content covers Android, iOS, front-end, back-end, blockchain, products, design, artificial intelligence and other fields. If you want to see more high-quality translation, please continue to pay attention to the Translation plan of Digging Gold, the official Weibo, Zhihu column.