search
HomeWeb Front-endJS TutorialAnalyzing confusing variable assignments in JavaScript_javascript tips

Javascript is a weakly typed language. When declaring a variable, you do not need to declare its type. Var x can be equal to any type of value.
For example:

var str = "string....";
var arr = ["this","is","array"];
var obj = {name :"caizhongqi",age:26,sex:"male"};
These are all correct. It seems very simple and convenient, but this convenience will also bring some elusive surprises. Take a look below Example (Example 1):




You may know at once that the alert comes out as "this is string", yes, but for programmers who use Java language , var y=x should assign the address (pointer) of x in the memory to the y variable, so they think that alerting "ni hao" should be more consistent with the Java language habits, but this is not the case with JavaScript language. Characters String assignment is a direct operation, directly copying the data to the storage space of y.

Look at the following example (Example 2):




If you thought the alert came out as "hello", you are wrong. When var y = x, hasn’t x already given its array to y? But in fact this is not the case. When var y = x, x passes its address (pointer) in the memory! x[0]="world" modifies the data in the original storage location, so alert(y[0]) uses the new value of x to alert. Confused? Why is it measured directly and quoted directly at one time?
Don’t worry, the following example will be more confusing (Example 3):




Your eyes tell you that the alert comes out as "hello"! This is so unpredictable and weird JavaScript!

There is a similar scene in Stephen Chow's "Domestic Zero Paint":
When Mr. Xing just arrived in Hong Kong from Shenzhen on a mission, Anita Yuen found a hair dryer in his luggage. I said it was actually a beard shaver, but when I took out my leather shoes, I saw it was a hair dryer, and what looked like a mobile phone was actually a beard shaver. The shaver and hairdryer confused Anita Yuen and the audience. Hahahaha, this is one of my favorite movies. My stomach hurt when I watched it for the first time.

Looking back at the variable assignment just now, the use of direct quantities and reference quantities is like exchanging a shaver with a hairdryer, which made us all dizzy.
In fact, the problem lies in the second assignment of x = ["ni", "hao"]. Let's take a look at the changes in the memory and the difference between JavaScript's treatment of string types and object types:

We observe the following two situations:
var x = "this is string...";
var y = ["this","is","string"];

The difference between x and y lies in the type. The JavaScript parser directly assigns the string value (actually copy) to x (direct quantity), but assigns the array pointer to y (reference quantity). All this happens instantly. Fully automatic! Combined with the following picture, you may have a better understanding:



In the picture, p1, p2... are pointers to variables, and the y in var y above stores Object type variables. The pointer p1 (assumed), and x stores the string itself. Analyze Example 3 again. When executing var ni","hao"], the parser opens up a new storage space to hold this new array, and x is the pointer of this new storage space. This means that the redefinition (or reassignment) of variables in JavaScript will Create a new storage space without destroying the original space; look back at Example 2, x[0] = "world", this sentence does not define a new value for x, does not create a new storage space, but only changes its storage The data in the space, so the final alert in Example 2 is "world"; Example 1 is a string assignment, and the whole process is a direct operation.

As can be seen from the above analysis, JavaScript variables can store direct quantities or pointers. This cannot be artificially interfered with. Therefore, in daily coding, you need to pay attention to these issues, such as Details such as large string concatenation and assignment in loops can directly affect the execution efficiency of the program.

Look at two examples:
var _tmpStr="";
var str = "this is big string...";
for (i=0; i _tmpStr = a;
}
a = _tmpStr;

Because it is a string operation, using direct quantities, each loop must operate a large string. Very bulky and inefficient. If you use reference operations instead, that is, through arrays:
var str = "this is big string...";
var _tmpArray = [];
for (i=0; i _tmpArray[i]=str;
} <script> var x = "this is string"; <BR> var y = x; <BR> x="ni hao"; <BR> alert(y) <BR></script>str = _tmpArray.join(""); <script> <BR>var x = ["hello"] // 这是一个数组,只有一个元素,并且该元素为字符串类型 <BR>var y = x; <BR>x[0] = "world"; <BR>alert(y[0]); <BR></script><script> <BR>var x = ["hello"] // 这是一个数组,只有一个元素,并且该元素为字符串类型 <BR>var y = x; <BR>x = ["ni","hao"]; // x 将变成一个新的数组了。 <BR>alert(y[0]); <BR></script>Do a test, if there is a 100k string, The direct connection operation takes about 2600 milliseconds on my machine. If the array connection is used, it takes 150 milliseconds. The efficiency is more than ten times different.

I haven’t written such a long article for a long time. It took me most of the day.

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
如何使用MySQL数据库进行预测和预测分析?如何使用MySQL数据库进行预测和预测分析?Jul 12, 2023 pm 08:43 PM

如何使用MySQL数据库进行预测和预测分析?概述:预测和预测分析在数据分析中扮演着重要角色。MySQL作为一种广泛使用的关系型数据库管理系统,也可以用于预测和预测分析任务。本文将介绍如何使用MySQL进行预测和预测分析,并提供相关的代码示例。数据准备:首先,我们需要准备相关的数据。假设我们要进行销售预测,我们需要具有销售数据的表。在MySQL中,我们可以使用

如何使用 Go 语言进行数据可视化分析?如何使用 Go 语言进行数据可视化分析?Jun 10, 2023 am 10:46 AM

随着大数据时代的到来,数据可视化分析在各行各业中扮演着至关重要的角色。而Go语言作为一种快速、高效、安全的编程语言,也逐渐在数据可视化分析领域占据一席之地。本文将探讨如何使用Go语言进行数据可视化分析。一、Go语言常用的数据可视化库Plotly:可用于在浏览器中创建交互式的图形,支持多种图形类型,如线图、条形图、散点图、热力图等。Gonum/plo

Linux下的实时日志监控与分析Linux下的实时日志监控与分析Jul 29, 2023 am 08:06 AM

Linux下的实时日志监控与分析在日常的系统管理和故障排查中,日志是一个非常重要的数据来源。通过对系统日志的实时监控和分析,我们可以及时发现异常情况并进行相应的处理。本文将介绍Linux下如何进行实时日志监控和分析,并提供相应的代码示例。一、实时日志监控在Linux下,最常用的日志系统是rsyslog。通过配置rsyslog,我们可以实现将不同应用程序的日志

统计分析法的步骤统计分析法的步骤Jun 28, 2023 pm 03:27 PM

统计分析,常指对收集到的有关数据资料进行整理归类并进行解释的过程。统计分析的基本步骤包括:1、收集数据;2、整理数据;3、分析数据。

如何使用PHP进行性能分析和调优如何使用PHP进行性能分析和调优Jun 06, 2023 pm 01:21 PM

作为一种流行的服务端语言,PHP在网站开发和运行中扮演着重要的角色。然而,随着PHP代码量的不断增加和应用程序的复杂性提高,性能瓶颈也越来越容易出现。为了避免这种问题,我们需要进行性能分析和调优。本文将简单介绍如何使用PHP进行性能分析和调优,为您的应用程序提供更高效的运行环境。一、PHP性能分析工具1.XdebugXdebug是一款广泛使用的代码分析工具,

最近大火的Diffusion Model,首篇扩散生成模型综述!最近大火的Diffusion Model,首篇扩散生成模型综述!Apr 09, 2023 pm 08:31 PM

本综述(Diffusion Models: A Comprehensive Survey of Methods and Applications)来自加州大学&amp;Google Research的Ming-Hsuan Yang、北京大学崔斌实验室以及CMU、UCLA、蒙特利尔Mila研究院等众研究团队,首次对现有的扩散生成模型(diffusion model)进行了全面的总结分析,从diffusion model算法细化分类、和其他五大生成模型的关联以及在七大领域中的应用等方面展开,

如何利用PHP和Elasticsearch实现结果聚合和分析如何利用PHP和Elasticsearch实现结果聚合和分析Jul 17, 2023 pm 01:05 PM

如何利用PHP和Elasticsearch实现结果聚合和分析引言:随着互联网和信息技术的迅猛发展,数据量的爆炸式增长使得数据的存储、处理、分析变得越来越重要。而Elasticsearch作为一个开源的分布式搜索和分析引擎,具有强大的全文检索、实时分析和数据聚合能力,已经被广泛应用于各大行业中。在本文中,我们将介绍如何利用PHP和Elasticsearch结合

如何使用 Go 语言进行大数据分析?如何使用 Go 语言进行大数据分析?Jun 11, 2023 am 11:11 AM

随着数据规模逐渐增大,大数据分析变得越来越重要。而Go语言作为一门快速、轻量级的编程语言,也成为了越来越多数据科学家和工程师的选择。本文将介绍如何使用Go语言进行大数据分析。数据采集在开始大数据分析之前,我们需要先采集数据。Go语言有很多包可以用于数据采集,例如“net/http”、“io/ioutil”等。通过这些包,我们可以从网站、API、日志

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)