1677145740
你應該知道的 10 大 JavaScript 數組方法:forEach()、includes()、filter()、map()、reduce()、some()、every()、sort()、Array.from()、Array.of (). 10 個重要的 JavaScript 數組方法
如果你對數組一竅不通,可以點此查看數組介紹。
這裡有 10 個你至少應該知道的 javascript 數組方法
第一的。forEach()
此方法可以幫助您遍歷數組的項目。
const arr = [1, 2, 3, 4, 5, 6];
arr.forEach(item => {
console.log(item); // output: 1 2 3 4 5 6
});
2.includes()
此方法檢查數組是否包含方法中傳遞的項目。
const arr = [1, 2, 3, 4, 5, 6];
arr.includes(2); // output: true
arr.includes(7); // output: false
3.filter()
此方法創建新數組,其中僅包含在提供的函數內傳遞條件的元素。
const arr = [1, 2, 3, 4, 5, 6];
// item(s) greater than 3
const filtered = arr.filter(num => num > 3);
console.log(filtered); // output: [4, 5, 6]
console.log(arr); // output: [1, 2, 3, 4, 5, 6]
4.map()
此方法通過在每個元素中調用提供的函數來創建新數組。
const arr = [1, 2, 3, 4, 5, 6];
// add one to every element
const oneAdded = arr.map(num => num + 1);
console.log(oneAdded); // output [2, 3, 4, 5, 6, 7]
console.log(arr); // output: [1, 2, 3, 4, 5, 6]
5.reduce()
reduce() 方法對累加器和數組中的每個元素(從左到右)應用一個函數以將其減少為單個值 - MDN
const arr = [1, 2, 3, 4, 5, 6];
const sum = arr.reduce((total, value) => total + value, 0);
console.log(sum); // 21
6.some()
此方法檢查數組的至少一項是否通過了條件。如果通過,則返回“true”,否則返回“false”。
const arr = [1, 2, 3, 4, 5, 6];
// at least one element is greater than 4?
const largeNum = arr.some(num => num > 4);
console.log(largeNum); // output: true
// at least one element is less than or equal to 0?
const smallNum = arr.some(num => num <= 0);
console.log(smallNum); // output: false
7.every()
此方法檢查是否所有數組的項目都通過了條件。如果通過,則返回“true”,否則返回“false”。
const arr = [1, 2, 3, 4, 5, 6];
// all elements are greater than 4
const greaterFour = arr.every(num => num > 4);
console.log(greaterFour); // output: false
// all elements are less than 10
const lessTen = arr.every(num => num < 10);
console.log(lessTen); // output: true
8.sort()
此方法用於按升序或降序排列/排序數組的項目。
const arr = [1, 2, 3, 4, 5, 6];
const alpha = ['e', 'a', 'c', 'u', 'y'];
// sort in descending order
descOrder = arr.sort((a, b) => a > b ? -1 : 1);
console.log(descOrder); // output: [6, 5, 4, 3, 2, 1]
// sort in ascending order
ascOrder = alpha.sort((a, b) => a > b ? 1 : -1);
console.log(ascOrder); // output: ['a', 'c', 'e', 'u', 'y']
9.Array.from()
這會將所有類似數組或可迭代的東西都變成真正的數組,尤其是在使用 DOM 時,這樣您就可以使用其他數組方法,如 reduce、map、filter 等。
const name = 'frugence';
const nameArray = Array.from(name);
console.log(name); // output: frugence
console.log(nameArray); // output: ['f', 'r', 'u', 'g', 'e', 'n', 'c', 'e']
使用 DOM
// I assume that you have created unorder list of items in our html file.
const lis = document.querySelectorAll('li');
const lisArray = Array.from(document.querySelectorAll('li'));
// is true array?
console.log(Array.isArray(lis)); // output: false
console.log(Array.isArray(lisArray)); // output: true
十。Array.of()
這從傳遞給它的每個參數創建數組。
const nums = Array.of(1, 2, 3, 4, 5, 6);
console.log(nums); // output: [1, 2, 3, 4, 5, 6]
#javascript
1622207074
Who invented JavaScript, how it works, as we have given information about Programming language in our previous article ( What is PHP ), but today we will talk about what is JavaScript, why JavaScript is used The Answers to all such questions and much other information about JavaScript, you are going to get here today. Hope this information will work for you.
JavaScript language was invented by Brendan Eich in 1995. JavaScript is inspired by Java Programming Language. The first name of JavaScript was Mocha which was named by Marc Andreessen, Marc Andreessen is the founder of Netscape and in the same year Mocha was renamed LiveScript, and later in December 1995, it was renamed JavaScript which is still in trend.
JavaScript is a client-side scripting language used with HTML (Hypertext Markup Language). JavaScript is an Interpreted / Oriented language called JS in programming language JavaScript code can be run on any normal web browser. To run the code of JavaScript, we have to enable JavaScript of Web Browser. But some web browsers already have JavaScript enabled.
Today almost all websites are using it as web technology, mind is that there is maximum scope in JavaScript in the coming time, so if you want to become a programmer, then you can be very beneficial to learn JavaScript.
In JavaScript, ‘document.write‘ is used to represent a string on a browser.
<script type="text/javascript">
document.write("Hello World!");
</script>
<script type="text/javascript">
//single line comment
/* document.write("Hello"); */
</script>
#javascript #javascript code #javascript hello world #what is javascript #who invented javascript
1616670795
It is said that a digital resource a business has must be interactive in nature, so the website or the business app should be interactive. How do you make the app interactive? With the use of JavaScript.
Does your business need an interactive website or app?
Hire Dedicated JavaScript Developer from WebClues Infotech as the developer we offer is highly skilled and expert in what they do. Our developers are collaborative in nature and work with complete transparency with the customers.
The technology used to develop the overall app by the developers from WebClues Infotech is at par with the latest available technology.
Get your business app with JavaScript
For more inquiry click here https://bit.ly/31eZyDZ
Book Free Interview: https://bit.ly/3dDShFg
#hire dedicated javascript developers #hire javascript developers #top javascript developers for hire #hire javascript developer #hire a freelancer for javascript developer #hire the best javascript developers
1589255577
As a JavaScript developer of any level, you need to understand its foundational concepts and some of the new ideas that help us developing code. In this article, we are going to review 16 basic concepts. So without further ado, let’s get to it.
#javascript-interview #javascript-development #javascript-fundamental #javascript #javascript-tips
1626321063
PixelCrayons: Our JavaScript web development service offers you a feature-packed & dynamic web application that effectively caters to your business challenges and provide you the best RoI. Our JavaScript web development company works on all major frameworks & libraries like Angular, React, Nodejs, Vue.js, to name a few.
With 15+ years of domain expertise, we have successfully delivered 13800+ projects and have successfully garnered 6800+ happy customers with 97%+ client retention rate.
Looking for professional JavaScript web app development services? We provide custom JavaScript development services applying latest version frameworks and libraries to propel businesses to the next level. Our well-defined and manageable JS development processes are balanced between cost, time and quality along with clear communication.
Our JavaScript development companies offers you strict NDA, 100% money back guarantee and agile/DevOps approach.
#javascript development company #javascript development services #javascript web development #javascript development #javascript web development services #javascript web development company
1670076960
Today, JavaScript is at the core of virtually all modern web applications. That’s why JavaScript issues, and finding the mistakes that cause them, are at the forefront for web developers.
Powerful JavaScript-based libraries and frameworks for single page application (SPA) development, graphics and animation, and server-side JavaScript platforms are nothing new. JavaScript has truly become ubiquitous in the world of web app development and is therefore an increasingly important skill to master.
At first, JavaScript may seem quite simple. And indeed, to build basic JavaScript functionality into a web page is a fairly straightforward task for any experienced software developer, even if they’re new to JavaScript. Yet the language is significantly more nuanced, powerful, and complex than one would initially be led to believe. Indeed, many of JavaScript’s subtleties lead to a number of common problems that keep it from working—10 of which we discuss here—that are important to be aware of and avoid in one’s quest to become a master JavaScript developer.
this
There’s no shortage of confusion among JavaScript developers regarding JavaScript’s this
keyword.
As JavaScript coding techniques and design patterns have become increasingly sophisticated over the years, there’s been a corresponding increase in the proliferation of self-referencing scopes within callbacks and closures, which are a fairly common source of “this
/that confusion” causing JavaScript issues.
Consider this example code snippet:
Game.prototype.restart = function () {
this.clearLocalStorage();
this.timer = setTimeout(function() {
this.clearBoard(); // What is "this"?
}, 0);
};
Executing the above code results in the following error:
Uncaught TypeError: undefined is not a function
Why? It’s all about context. The reason you get the above error is because, when you invoke setTimeout()
, you are actually invoking window.setTimeout()
. As a result, the anonymous function being passed to setTimeout()
is being defined in the context of the window
object, which has no clearBoard()
method.
A traditional, old-browser-compliant solution is to simply save your reference to this
in a variable that can then be inherited by the closure; e.g.:
Game.prototype.restart = function () {
this.clearLocalStorage();
var self = this; // Save reference to 'this', while it's still this!
this.timer = setTimeout(function(){
self.clearBoard(); // Oh OK, I do know who 'self' is!
}, 0);
};
Alternatively, in newer browsers, you can use the bind()
method to pass in the proper reference:
Game.prototype.restart = function () {
this.clearLocalStorage();
this.timer = setTimeout(this.reset.bind(this), 0); // Bind to 'this'
};
Game.prototype.reset = function(){
this.clearBoard(); // Ahhh, back in the context of the right 'this'!
};
As discussed in our JavaScript Hiring Guide, a common source of confusion among JavaScript developers (and therefore a common source of bugs) is assuming that JavaScript creates a new scope for each code block. Although this is true in many other languages, it is not true in JavaScript. Consider, for example, the following code:
for (var i = 0; i < 10; i++) {
/* ... */
}
console.log(i); // What will this output?
If you guess that the console.log()
call would either output undefined
or throw an error, you guessed incorrectly. Believe it or not, it will output 10
. Why?
In most other languages, the code above would lead to an error because the “life” (i.e., scope) of the variable i
would be restricted to the for
block. In JavaScript, though, this is not the case and the variable i
remains in scope even after the for
loop has completed, retaining its last value after exiting the loop. (This behavior is known, incidentally, as variable hoisting.)
Support for block-level scopes in JavaScript is available via the let
keyword. The let
keyword has been widely supported by browsers and back-end JavaScript engines like Node.js for years now..
If that’s news to you, it’s worth taking the time to read up on scopes, prototypes, and more.
Memory leaks are almost inevitable JavaScript issues if you’re not consciously coding to avoid them. There are numerous ways for them to occur, so we’ll just highlight a couple of their more common occurrences.
Consider the following code:
var theThing = null;
var replaceThing = function () {
var priorThing = theThing; // Hold on to the prior thing
var unused = function () {
// 'unused' is the only place where 'priorThing' is referenced,
// but 'unused' never gets invoked
if (priorThing) {
console.log("hi");
}
};
theThing = {
longStr: new Array(1000000).join('*'), // Create a 1MB object
someMethod: function () {
console.log(someMessage);
}
};
};
setInterval(replaceThing, 1000); // Invoke `replaceThing' once every second
If you run the above code and monitor memory usage, you’ll find that you’ve got a significant memory leak, leaking a full megabyte per second! And even a manual Garbage Collector (GC) doesn’t help. So it looks like we are leaking longStr
every time replaceThing
is called. But why?
Memory leaks are almost inevitable JavaScript issues if you’re not consciously coding to avoid them.
Let’s examine things in more detail:
Each theThing
object contains its own 1MB longStr
object. Every second, when we call replaceThing
, it holds on to a reference to the prior theThing
object in priorThing
. But we still wouldn’t think this would be a problem, since each time through, the previously referenced priorThing
would be dereferenced (when priorThing
is reset via priorThing = theThing;
). And moreover, is only referenced in the main body of replaceThing
and in the function unused
which is, in fact, never used.
So again we’re left wondering why there is a memory leak here.
To understand what’s going on, we need to better understand the inner workings of JavaScript. The typical way that closures are implemented is that every function object has a link to a dictionary-style object representing its lexical scope. If both functions defined inside replaceThing
actually used priorThing
, it would be important that they both get the same object, even if priorThing
gets assigned to over and over, so both functions share the same lexical environment. But as soon as a variable is used by any closure, it ends up in the lexical environment shared by all closures in that scope. And that little nuance is what leads to this gnarly memory leak.
Consider this code fragment:
function addClickHandler(element) {
element.click = function onClick(e) {
alert("Clicked the " + element.nodeName)
}
}
Here, onClick
has a closure that keeps a reference to element
(via element.nodeName
). By also assigning onClick
to element.click
, the circular reference is created; i.e.: element
→ onClick
→ element
→ onClick
→ element
…
Interestingly, even if element
is removed from the DOM, the circular self-reference above would prevent element
and onClick
from being collected, and hence, a memory leak.
JavaScript’s memory management (and, in particular, garbage collection) is largely based on the notion of object reachability.
The following objects are assumed to be reachable and are known as “roots”:
Objects are kept in memory at least as long as they are accessible from any of the roots through a reference, or a chain of references.
There is a Garbage Collector in the browser that cleans memory occupied by unreachable objects; in other words, objects will be removed from memory if and only if the GC believes that they are unreachable. Unfortunately, it’s fairly easy to end up with defunct “zombie” objects that are no longer in use but that the GC still thinks are “reachable.”
One of the conveniences in JavaScript is that it will automatically coerce any value being referenced in a boolean context to a boolean value. But there are cases where this can be as confusing as it is convenient. Some of the following, for example, have been known to be troublesome for many a JavaScript developer:
// All of these evaluate to 'true'!
console.log(false == '0');
console.log(null == undefined);
console.log(" \t\r\n" == 0);
console.log('' == 0);
// And these do too!
if ({}) // ...
if ([]) // ...
With regard to the last two, despite being empty (which might lead one to believe that they would evaluate to false
), both {}
and []
are in fact objects and any object will be coerced to a boolean value of true
in JavaScript, consistent with the ECMA-262 specification.
As these examples demonstrate, the rules of type coercion can sometimes be clear as mud. Accordingly, unless type coercion is explicitly desired, it’s typically best to use ===
and !==
(rather than ==
and !=
), so as to avoid any unintended side effects of type coercion. (==
and !=
automatically perform type conversion when comparing two things, whereas ===
and !==
do the same comparison without type conversion.)
And completely as a sidepoint—but since we’re talking about type coercion and comparisons—it’s worth mentioning that comparing NaN
with anything (even NaN
!) will always return false
. You therefore cannot use the equality operators (==
, ===
, !=
, !==
) to determine whether a value is NaN
or not. Instead, use the built-in global isNaN()
function:
console.log(NaN == NaN); // False
console.log(NaN === NaN); // False
console.log(isNaN(NaN)); // True
JavaScript makes it relatively easy to manipulate the DOM (i.e., add, modify, and remove elements), but does nothing to promote doing so efficiently.
A common example is code that adds a series of DOM Elements one at a time. Adding a DOM element is an expensive operation. Code that adds multiple DOM elements consecutively is inefficient and likely not to work well.
One effective alternative when multiple DOM elements need to be added is to use document fragments instead, thereby improving efficiency and performance.
For example:
var div = document.getElementsByTagName("my_div");
var fragment = document.createDocumentFragment();
for (var e = 0; e < elems.length; e++) { // elems previously set to list of elements
fragment.appendChild(elems[e]);
}
div.appendChild(fragment.cloneNode(true));
In addition to the inherently improved efficiency of this approach, creating attached DOM elements is expensive, whereas creating and modifying them while detached and then attaching them yields much better performance.
for
LoopsConsider this code:
var elements = document.getElementsByTagName('input');
var n = elements.length; // Assume we have 10 elements for this example
for (var i = 0; i < n; i++) {
elements[i].onclick = function() {
console.log("This is element #" + i);
};
}
Based on the above code, if there were 10 input elements, clicking any of them would display “This is element #10”! This is because, by the time onclick
is invoked for any of the elements, the above for
loop will have completed and the value of i
will already be 10 (for all of them).
Here’s how we can correct the aforementioned problems with JavaScript to achieve the desired behavior:
var elements = document.getElementsByTagName('input');
var n = elements.length; // Assume we have 10 elements for this example
var makeHandler = function(num) { // Outer function
return function() { // Inner function
console.log("This is element #" + num);
};
};
for (var i = 0; i < n; i++) {
elements[i].onclick = makeHandler(i+1);
}
In this revised version of the code, makeHandler
is immediately executed each time we pass through the loop, each time receiving the then-current value of i+1
and binding it to a scoped num
variable. The outer function returns the inner function (which also uses this scoped num
variable) and the element’s onclick
is set to that inner function. This ensures that each onclick
receives and uses the proper i
value (via the scoped num
variable).
A surprisingly high percentage of JavaScript developers fail to fully understand, and therefore to fully leverage, the features of prototypal inheritance.
Here’s a simple example. Consider this code:
BaseObject = function(name) {
if (typeof name !== "undefined") {
this.name = name;
} else {
this.name = 'default'
}
};
Seems fairly straightforward. If you provide a name, use it, otherwise set the name to ‘default’. For instance:
var firstObj = new BaseObject();
var secondObj = new BaseObject('unique');
console.log(firstObj.name); // -> Results in 'default'
console.log(secondObj.name); // -> Results in 'unique'
But what if we were to do this:
delete secondObj.name;
We’d then get:
console.log(secondObj.name); // -> Results in 'undefined'
But wouldn’t it be nicer for this to revert to ‘default’? This can easily be done, if we modify the original code to leverage prototypal inheritance, as follows:
BaseObject = function (name) {
if(typeof name !== "undefined") {
this.name = name;
}
};
BaseObject.prototype.name = 'default';
With this version, BaseObject
inherits the name
property from its prototype
object, where it is set (by default) to 'default'
. Thus, if the constructor is called without a name, the name will default to default
. And similarly, if the name
property is removed from an instance of BaseObject
, the prototype chain will then be searched and the name
property will be retrieved from the prototype
object where its value is still 'default'
. So now we get:
var thirdObj = new BaseObject('unique');
console.log(thirdObj.name); // -> Results in 'unique'
delete thirdObj.name;
console.log(thirdObj.name); // -> Results in 'default'
Let’s define a simple object, and create an instance of it, as follows:
var MyObject = function() {}
MyObject.prototype.whoAmI = function() {
console.log(this === window ? "window" : "MyObj");
};
var obj = new MyObject();
Now, for convenience, let’s create a reference to the whoAmI
method, presumably so we can access it merely by whoAmI()
rather than the longer obj.whoAmI()
:
var whoAmI = obj.whoAmI;
And just to be sure everything looks copacetic, let’s print out the value of our new whoAmI
variable:
console.log(whoAmI);
Outputs:
function () {
console.log(this === window ? "window" : "MyObj");
}
Okay, cool. Looks fine.
But now, look at the difference when we invoke obj.whoAmI()
vs. our convenience reference whoAmI()
:
obj.whoAmI(); // Outputs "MyObj" (as expected)
whoAmI(); // Outputs "window" (uh-oh!)
What went wrong? When we did the assignment var whoAmI = obj.whoAmI;
, the new variable whoAmI
was being defined in the global namespace. As a result, its value of this
is window
, not the obj
instance of MyObject
!
Thus, if we really need to create a reference to an existing method of an object, we need to be sure to do it within that object’s namespace, to preserve the value of this
. One way of doing this would be as follows:
var MyObject = function() {}
MyObject.prototype.whoAmI = function() {
console.log(this === window ? "window" : "MyObj");
};
var obj = new MyObject();
obj.w = obj.whoAmI; // Still in the obj namespace
obj.whoAmI(); // Outputs "MyObj" (as expected)
obj.w(); // Outputs "MyObj" (as expected)
setTimeout
or setInterval
For starters, let’s be clear on something here: Providing a string as the first argument to setTimeout
or setInterval
is not itself a mistake per se. It is perfectly legitimate JavaScript code. The issue here is more one of performance and efficiency. What is rarely explained is that if you pass in a string as the first argument to setTimeout
or setInterval
, it will be passed to the function constructor to be converted into a new function. This process can be slow and inefficient, and is rarely necessary.
The alternative to passing a string as the first argument to these methods is to instead pass in a function. Let’s take a look at an example.
Here, then, would be a fairly typical use of setInterval
and setTimeout
, passing a string as the first parameter:
setInterval("logTime()", 1000);
setTimeout("logMessage('" + msgValue + "')", 1000);
The better choice would be to pass in a function as the initial argument; e.g.:
setInterval(logTime, 1000); // Passing the logTime function to setInterval
setTimeout(function() { // Passing an anonymous function to setTimeout
logMessage(msgValue); // (msgValue is still accessible in this scope)
}, 1000);
As explained in our JavaScript Hiring Guide, “strict mode” (i.e., including 'use strict';
at the beginning of your JavaScript source files) is a way to voluntarily enforce stricter parsing and error handling on your JavaScript code at runtime, as well as making it more secure.
While, admittedly, failing to use strict mode is not a “mistake” per se, its use is increasingly being encouraged and its omission is increasingly becoming considered bad form.
Here are some key benefits of strict mode:
this
coercion. Without strict mode, a reference to a this
value of null or undefined is automatically coerced to the global. This can cause many frustrating bugs. In strict mode, referencing a this
value of null or undefined throws an error.var object = {foo: "bar", foo: "baz"};
) or a duplicate named argument for a function (e.g., function foo(val1, val2, val1){}
), thereby catching what is almost certainly a bug in your code that you might otherwise have wasted lots of time tracking down.eval()
behaves in strict mode and in nonstrict mode. Most significantly, in strict mode, variables and functions declared inside an eval()
statement are not created in the containing scope. (They are created in the containing scope in nonstrict mode, which can also be a common source of problems with JavaScript.)delete
. The delete
operator (used to remove properties from objects) cannot be used on nonconfigurable properties of the object. Nonstrict code will fail silently when an attempt is made to delete a nonconfigurable property, whereas strict mode will throw an error in such a case.As is true with any technology, the better you understand why and how JavaScript works and doesn’t work, the more solid your code will be and the more you’ll be able to effectively harness the true power of the language. Conversely, lack of proper understanding of JavaScript paradigms and concepts is indeed where many JavaScript problems lie.
Thoroughly familiarizing yourself with the language’s nuances and subtleties is the most effective strategy for improving your proficiency and increasing your productivity. Avoiding many common JavaScript mistakes will help when your JavaScript is not working.
Original article source at: https://www.toptal.com/