js值传递和引用传递

若依前后端分离版集成nacos 服务动态配置与服务注册发现根据公司要求,需要将项目集成到nacos中,当前项目是基于若依前后端分离版开发的,若依的版本为3.8.3,若依框架中整合的springBoot版本为2.5.14。Nacos核心提供两个功能:服务注册与发现,动态配置管理。 阅读详情
Previous Page
Next Page

3.15. By Value Versus by Reference

In JavaScript, as in all programming languages, you can manipulate a data value in three important ways.[*] First, you can copy it. For example, you might assign it to a new variable. Second, you can pass it as an argument to a function or method. Third, you can compare it with another value to see whether the two values are equal. To understand any programming language, you must understand how these three operations are performed in that language.

[*] This section covers advanced material, which you may want to skip on your first reading.

There are two fundamentally distinct ways to manipulate data values. These techniques are called by value and by reference. When a datum is manipulated by value, it is the value of the datum that matters. In an assignment, a copy of the actual value is made, and that copy is stored in a variable, object property, or array element; the copy and the original are two totally independent values that are stored separately. When a datum is passed by value to a function, a copy of the datum is passed to the function; if the function modifies the value, the change affects only the function's copy of the datumit does not affect the original datum. Finally, when a datum is compared by value to another datum, the two distinct pieces of data must represent exactly the same value (which usually means that a byte-by-byte comparison finds them to be equal).

The other way to manipulate a value is by reference. With this technique, there is only one actual copy of the value; references to that value are manipulated.[] If a value is manipulated by reference, variables do not hold that value directly; they hold only references to it. It is these references that are copied, passed, and compared. So, in an assignment made by reference, it is the reference to the value that is assigned, not a copy of the value and not the value itself. After the assignment, the new variable refers to the same value that the original variable refers to. Both references are equally valid, and both can be used to manipulate the value; if the value is changed through one reference, that change also appears through the original reference. The situation is similar when a value is passed to a function by reference. A reference to the value is passed to the function, and the function can use that reference to modify the value itself; any such modifications are visible outside the function. Finally, when a value is compared to another by reference, the two references are compared to see if they refer to the same unique copy of a value; references to two distinct values that happen to be equivalent (i.e., consist of the same bytes) are not treated as equal.

[] C programmers and anyone else familiar with the concept of pointers should understand the idea of a reference in this context. Note, however, that JavaScript does not support pointers.

These are two very different ways of manipulating values, and they have important implications that you should understand. Table 3-4 summarizes these implications. This discussion of manipulating data by value and by reference has been a general one, but the distinctions apply to all programming languages. The sections that follow explain how these distinctions apply specifically to JavaScript; they discuss which datatypes are manipulated by value and which are manipulated by reference.

Table 3-4. By value versus by reference

By value

By reference

Copy

The value is actually copied; there are two distinct, independent copies.

Only a reference to the value is copied. If the value is modified through the new reference, that change is also visible through the original reference.

Pass

A distinct copy of the value is passed to the function; changes to it have no effect outside the function.

A reference to the value is passed to the function. If the function modifies the value through the passed reference, the modification is visible outside the function.

Compare

Two distinct values are compared (often byte by byte) to see if they are the same value.

Two references are compared to see if they refer to the same value. Two references to distinct values are not equal, even if the two values consist of the same bytes.


3.15.1. Primitive Types and Reference Types

The basic rule in JavaScript is this: primitive types are manipulated by value, and reference types, as the name suggests, are manipulated by reference. Numbers and booleans are primitive types in JavaScriptprimitive because they consist of nothing more than a small, fixed number of bytes that are easily manipulated at the low levels of the JavaScript interpreter. Objects, on the other hand, are reference types. Arrays and functions, which are specialized types of objects, are therefore also reference types. These datatypes can contain arbitrary numbers of properties or elements, so they cannot be manipulated as easily as fixed-size primitive values can. Since object and array values can become quite large, it doesn't make sense to manipulate these types by value, because this could involve the inefficient copying and comparing of large amounts of memory.

What about strings? A string can have an arbitrary length, so it would seem that strings should be reference types. In fact, though, they are usually considered primitive types in JavaScript simply because they are not objects. Strings don't actually fit into the primitive-versus-reference type dichotomy. I'll explain more about strings and their behavior a little later.

The best way to explore the differences between data manipulation by value and by reference is through example. Study the following examples carefully, paying attention to the comments. Example 3-1 copies, passes, and compares numbers. Since numbers are primitive types, this example illustrates data manipulation by value.

Example 3-1. Copying, passing, and comparing by value

// First we illustrate copying by value
var n = 1;  // Variable n holds the value 1
var m = n;  // Copy by value: variable m holds a distinct value 1

// Here's a function we'll use to illustrate passing by value
// As we'll see, the function doesn't work the way we'd like it to
function add_to_total(total, x)
{
    total = total + x;  // This line changes only the internal copy of total
}

// Now call the function, passing the numbers contained in n and m by value.
// The value of n is copied, and that copied value is named total within the
// function. The function adds a copy of m to that copy of n. But adding
// something to a copy of n doesn't affect the original value of n outside
// of the function. So calling this function doesn't accomplish anything.
add_to_total(n, m);

// Now, we'll look at comparison by value.
// In the following line of code, the literal 1 is clearly a distinct numeric
// value encoded in the program. We compare it to the value held in variable
// n. In comparison by value, the bytes of the two numbers are checked to
// see if they are the same.
if (n == 1) m = 2;  // n contains the same value as the literal 1; m is now 2

Now, consider Example 3-2. This example copies, passes, and compares an object. Since objects are reference types, these manipulations are performed by reference. This example uses Date objects, which you can read more about in Part III.

Example 3-2. Copying, passing, and comparing by reference

// Here we create an object representing the date of Christmas, 2007
// The variable xmas contains a reference to the object, not the object itself
var xmas = new Date(2007, 11, 25);
// When we copy by reference, we get a new reference to the original object
var solstice = xmas;  // Both variables now refer to the same object value

// Here we change the object through our new reference to it
solstice.setDate(21);

// The change is visible through the original reference, as well
xmas.getDate( );  // Returns 21, not the original value of 25

// The same is true when objects and arrays are passed to functions.
// The following function adds a value to each element of an array.
// A reference to the array is passed to the function, not a copy of the array.
// Therefore, the function can change the contents of the array through
// the reference, and those changes will be visible when the function returns.
function add_to_totals(totals, x)
{
    totals[0] = totals[0] + x;
    totals[1] = totals[1] + x;
    totals[2] = totals[2] + x;
}

// Finally, we'll examine comparison by reference.
// When we compare the two variables defined above, we find they are
// equal, because they refer to the same object, even though we were trying
// to make them refer to different dates:
(xmas == solstice)  // Evaluates to true

// The two variables defined next refer to two distinct objects, both
// of which represent exactly the same date.
var xmas = new Date(2007, 11, 25);
var solstice_plus_4 = new Date(2007, 11, 25);

// But, by the rules of "compare by reference," distinct objects are not equal!
(xmas != solstice_plus_4)  // Evaluates to true

Before we leave the topic of manipulating objects and arrays by reference, let's clear up a point of nomenclature. The phrase "pass by reference" can have several meanings. To some readers, the phrase refers to a function-invocation technique that allows a function to assign new values to its arguments and to have those modified values visible outside the function. This is not the way the term is used in this book. Here, I mean simply that a reference to an object or arraynot the object itselfis passed to a function. A function can use the reference to modify properties of the object or elements of the array. But if the function overwrites the reference with a reference to a new object or array, that modification is not visible outside the function. Readers familiar with the other meaning of this term may prefer to say that objects and arrays are passed by value, but the value that is passed is actually a reference rather than the object itself. Example 3-3 illustrates this issue.

Example 3-3. References themselves are passed by value

// This is another version of the add_to_totals( ) function. It doesn't
// work, though, because instead of changing the array itself, it tries to
// change the reference to the array.
function add_to_totals2(totals, x)
{
    newtotals = new Array(3);
    newtotals[0] = totals[0] + x;
    newtotals[1] = totals[1] + x;
    newtotals[2] = totals[2] + x;
    totals = newtotals;  // This line has no effect outside of the function
}

3.15.2. Copying and Passing Strings

As mentioned earlier, JavaScript strings don't fit neatly into the primitive-versus-reference type dichotomy. Since strings are not objects, it is natural to assume that they are primitive. If they are primitive types, then by the rules given above, they should be manipulated by value. But since strings can be arbitrarily long, it would seem inefficient to copy, pass, and compare them byte by byte. Therefore, it would also be natural to assume that strings are implemented as reference types.

Instead of making assumptions about strings, let's write some JavaScript code to experiment with string manipulation. If strings are copied and passed by reference, you should be able to modify the contents of a string through the reference stored in another variable or passed to a function.

When setting out to write the code to perform this experiment, however, you'll run into a major stumbling block: there is no way to modify the contents of a string. The charAt( ) method returns the character at a given position in a string, but there is no corresponding setCharAt( ) method. This is not an oversight. JavaScript strings are intentionally immutablethat is, there is no JavaScript syntax, method, or property that allows you to change the characters in a string.

Since strings are immutable, the original question is moot: there is no way to tell whether strings are passed by value or by reference. You can assume that, for efficiency, JavaScript is implemented so that strings are passed by reference, but in actuality it doesn't matter, because it has no practical bearing on the code you write.

3.15.3. Comparing Strings

Despite the fact that you cannot determine whether strings are copied and passed by value or by reference, you can write JavaScript code to determine whether they are compared by value or by reference. Example 3-4 shows the code that can make this determination.

Example 3-4. Are strings compared by value or by reference?

// Determining whether strings are compared by value or reference is easy.
// We compare two clearly distinct strings that happen to contain the same
// characters. If they are compared by value they will be equal, but if they
// are compared by reference, they will not be equal:
var s1 = "hello";
var s2 = "hell" + "o";
if (s1 == s2) document.write("Strings compared by value");

This experiment demonstrates that strings are compared by value. This may be surprising to some programmers. In C, C++, and Java, strings are reference types and are compared by reference. If you want to compare the actual contents of two strings, you must use a special method or function. JavaScript, however, is a higher-level language and recognizes that when you compare strings, you most often want to compare them by value. Thus, despite the fact that, for efficiency, JavaScript strings are (presumably) copied and passed by reference, they are compared by value.

3.15.4. By Value Versus by Reference: Summary

Table 3-5 summarizes the way that the various JavaScript types are manipulated.

Table 3-5. Datatype manipulation in JavaScript

Type

Copied by

Passed by

Compared by

number

Value

Value

Value

boolean

Value

Value

Value

string

Immutable

Immutable

Value

object

Reference

Reference

Reference



Previous Page
Next Page
Godot4 TileMap分层绘制全攻略:解决角色、树木遮挡混乱,打造正确视觉层级 本文详细介绍了Godot4 TileMap分层绘制技术,通过图层管理和Y-Sort功能解决2D游戏中角色与物体的遮挡问题。从基础图层设置到高级优化策略,帮助开发者打造符合自然视觉规律的场景层次,提升游戏沉浸感。特别针对TileMap和TileSet的使用提供了实用技巧和代码示例。 阅读详情

相关推荐

ISP之LSC(Lens Shading Correction)

LSC - Lens Shading Correction即镜头暗影校正。

IQ_WXY的博客 5098

JS参数传递(值传递和引用传递)

前端红宝书第一遍看过去之后,相当多的东西都忘记了,第二遍看的时候,也开始注意到一些细节的东西以及理解不到位的地方。书P66 一个加粗框中写到:ECMAScript中所有参数传递都是值,不可能通过引用传递参数当时看过没有怎么仔细想过,一知半解吧,今天理解的更加深一些。当然也是昨天做了个题目就因为这个掉坑里一时没爬出来!访问变量有按值和按引用两种方式,而参数只能按值传递。一、基本数据类型: Numbe...

weixin_39728230的博客 6万+

Spatio-Temporal Graph Convolutional Networks: A Deep Learning Framework for Traffic Forecasting 论文笔记

Spatio-Temporal Graph Convolutional Networks: A Deep Learning Framework for Traffic Forecasting 论文笔记-----GCN在交通领域的应用(二) 一、论文翻译: 1、摘要: 及时准确地交通预测对于城市交通控制和指导具有至关重要的意义。由于交通流量的非线性和复杂性,传统的方法不能满足中长期预测任务的需求,并且往往会忽略时空数据的时间和空间依赖特性。在这篇论文中,为了处理在交通领域的时间序列预测问题...

cy_believ的博客 1916

java 值传递 js_深入理解JavaScript的值传递和引用传递

JavaScript有5种基本的数据类型,分别是:布尔、null、undefined、String和Number。这些基本类型在赋值的时候是通过值传递的方式。值得注意的是还有另外三种类型: Array、Function和Object,它们通过引用来传递。从底层技术上看,它们三都是对象。基本数据类型如果一个基本的数据类型绑定到某个变量,我们可以认为该变量包含这个基本数据类型的值。var x = 10...

weixin_42443797的博客 364

Axure rp9 中继器新建表格

Axure rp9 中继器新建表格

weixin_49295490的博客 1652

DeepQA: A Unified Transcriptome-Based Aging Clock Using Deep Neural Networks

摘要: 本研究针对转录组衰老时钟存在的关键局限——仅在健康样本训练导致对患病个体预测偏差的问题,提出DeepQA,一种基于专家混合架构与新型Hinge-MAE损失函数的深度学习模型。通过同时利用健康与患病个体的异质数据训练,DeepQA显著提升预测精度:在健康个体上MAE比现有方法低1.5年,且是首个能正确处理五类疾病条件的模型。其创新性体现在: 方法学突破:Hinge-MAE损失函数消除健康/患病样本的训练偏差,专家混合架构高效整合多队列数据; 流程革新:摒弃传统基因预筛选步骤,通过显著图分析直接识别衰老

qq_44050612的博客 125

JavaScript的值传递和引用传递

JavaScript有5种基本的数据类型,分别是:布尔、null、undefined、String和Number。这些基本类型在赋值的时候是通过值传递的方式。值得注意的是还有另外三种类型: Array、Function和Object,它们通过引用来传递。从底层技术上看,它们三都是对象。 基本数据类型 如果一个基本的数据类型绑定到某个变量,我们可以认为该变量包含这个基本数据类型的值。 var x = 10; var y = 'abc'; var z = null; 当我们使用=将这些变量赋值到..

qq_21987433的博客 698

深度学习实战35-图卷积神经网络GCN模型的搭建与应用

大家好,我是微学AI,今天给大家介绍一下深度学习实战35-图卷积神经网络GCN模型的搭建与应用,GCN是一种用于处理图结构数据的深度学习模型,它可以捕捉节点之间的拓扑关系和局部特征,并进行图级别的预测和分类任务。下面将介绍如何搭建并应用GCN模型。

微学AI的博客 2226

JavaScript进阶(三) 值传递和引用传递

从C语言开始

Javaallstar的专栏 3955

[STC32G144K246入门第三步]驱动串口收发(接收不定长数据)

本文介绍了STC32G144K246单片机的串口功能配置与使用。该芯片具有8组独立USART,支持异步/同步模式,各串口可独立配置波特率并支持DMA传输。重点讲解了串口寄存器配置方法,包括引脚设置、波特率计算和中断处理。特别指出RX引脚需配置为开漏或准双向口以避免接收乱码。还介绍了通过定时器实现不定长数据接收的技术方案,并提供了完整的初始化代码和中断处理函数示例。文中包含串口时序图、寄存器配置表等实用参考信息,适合嵌入式开发者快速上手多串口应用开发。

sinat_58149788的博客 195

2026华为OD面试题084:贪心的商人

商人经营一家店铺,有 `number` 种商品。由于仓库限制,每件商品的最大持有数量是 `item[index]`。 每种商品每天有一个价格 `item_price[item_index][day]`。通过对商品买进和卖出获取利润,请给出商人在 `days` 天内能获取到的最大利润。 注:同一件商品可以反复买进和卖出。 输入描述: - 第一行输入商品数量 `number` - 第二行输入商人售货天数 `days` - 第三行输入 `number` 个整数,表示每件商品的最大持有数量 `item[in

琅嬛福地 273

js数组和对象 值传递和引用

js数组和对象分为值传递和引用俩种方式。 对象的值传递 let arr={a:1,b:2} let row =Object.assign({}, arr);//row对象之后的操作不会影响到源对象arr 可能有些人对assign不太了解,看一下下面代码就会知道如何使用 Object.assign(target, ...sources); target 是目标对象 sources 是源对象 ...

木贝西的博客 2297

OpenClaw进阶实战(二十五):抖音企业号——私信回复与视频评论分析

本文介绍了抖音企业号自动化运营的技术方案,重点解决私信互动效率低和风控严格两大挑战。文章分析了抖音集成的三大技术壁垒(视频复杂性、风控体系、封闭API)并对比了三种技术路径的优缺点。针对不同规模的运营主体,推荐官方API+RPA混合架构或真机RPA+AI辅助的方案。 详细讲解了环境准备步骤,包括抖音Skill安装、Cookie获取和配置文件设置。核心实现部分展示了私信自动回复功能的安全合规实现,包含意图分类、优先级排序、延迟发送等防封禁机制,并提供了完整的Python代码示例。该方案通过模拟人工操作、限制日

PeterPan的博客 159

JavaScript中栈和堆,值传递和引用传递

JavaScript中栈和堆,值传递和引用传递基本数据类型和引用数据类型栈和堆1. const定义一个变量是不是不可变的2. 数据赋值3. 值传递和引用传递4. 栈内存和堆内存的优缺点 基本数据类型和引用数据类型 在讲什么是栈和堆之前我们首先要知道为什么会有这种东西,我们都知道JavaScript中的数据类型有两种,基本数据类型和引用数据类型。这两种数据有什么区别呢,最大的区别就是基本数据类型是存在栈中,引用类型存在堆中。下面有关于栈和堆的详细讲解 栈和堆 在js引擎中对变量的存储主要有两种位置,堆内存和栈

qq_43742385的博客 381

VB摄像头监控

该VB模块可对摄像头捕获的画面进行录像等,可在创建的窗口进行控制

假人有限元模型

假人模型,车辆碰撞假人有限元模型,适合做乘员安全的研究者利用

js-值传递和引用传递实例代码

js-值传递和引用传递实例代码 <!doctype html> <html> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <script> //按

前端博客 645

lwip-2.0.3

lwip是瑞典计算机科学院(SICS)的Adam Dunkels 开发的一个小型开源的TCP/IP协议栈。实现的重点是在保持TCP协议主要功能的基础上减少对RAM 的占用。

JavaScript 值传递和引用传递

先来看两个个来自于 《JavaScript 高级程序设计》P70-P71 的两个例子。 1.1. 基本类型参数传递 function addTen(num) { num += 10; return num; } var count = 20; var result = addTen(count); alert(count); // 20, 没有变化 alert(result); // 30 书上解释说,JavaScript 参数传递都是按值传参。 所以传递给 addTen 函数的值是 20 这个

猫影 676

JavaScript的值传递和引用传递的区别

前言、JavaScript 数据类型 首先要清楚JavaScript包含哪些数据类型,字符串(String)、数字(Number)、布尔(Boolean)、函数(Function())、数组(Array)、对象(Object)、空(Null)、未定义(Undefined)是JavaScript常见的数据类型。 一、值传递 JavaScript值传递的数据类型:字符串(String)、数字(N...

木易慕翊 1609

c语言值传递和引用传递的区别_JS中函数参数值传递和引用传递

在JavaScript红宝书中说到,“ECMAScript中所有函数的参数都是按值传递的”。理解这个概念先要从JS的堆内存和栈内存说起:栈内存为自动分配的内存空间,它由系统自动释放;堆内存则是动态分配的内存,大小不定也不会自动释放。(很初级的理解,有错误还望指正)JS中的5种基本数据类型Undefined、Null、Boolean、Number 和 String,它们是直接按值存放在栈内存中,可以...

weixin_31493023的博客 303

JavaScript基础之值传递和引用传递

js的值传递和引用(地址)传递 首先总述一下:js的5种基本数据类型 number,string,null,undefined,boolean 在赋值传递时是值传递,js的引用数据类型(object,array,function)进行引用传递,其实底层都是对象。 废话不多说,下面直接上代码 值传递例子: 1 var a = 10; 2 var b = a; 3 b = 5; 4 ...

weixin_33897722的博客 110

JS-堆栈-值传递和引用传递

复制过去的是地址,他们指向同一片内存。

Yous的博客 155

论javascript函数参数的值传递和引用传递

论javascript函数参数的值传递和引用传递        众所周知,在JavaScript里调用函数传参的方式分为值传递和引用传递两中方式,在这里我们来研究一下,值传递和引用传递的区别。        首先我们拿概念来说,在js函数传参时,如果传递的是数值类型的数据我们称之为“值传递”,如果传递的是对像类型的数据...

z1808232384的博客 366

深入理解JavaScript的值传递和引用传递

JavaScript有5种基本的数据类型,分别是:布尔、null、undefined、String和Number。这些基本类型在赋值的时候是通过值传递的方式。值得注意的是还有另外三种类型: Array、Function和Object,它们通过引用来传递。从底层技术上看,它们三都是对象。 基本数据类型 如果一个基本的数据类型绑定到某个变量,我们可以认为该变量包含这个基本数据类型的值。 ...

你如今的气质里,藏着你走过的路,经历过的事,读过的书,和爱过的人。 272

谈谈我对JavaScript值传递和引用传递的理解

数据类型 ECMAScript 标准定义了 7 种数据类型:

qq_43615908的博客 218

js中的值传递和引用传递

在js中值传递和引用传递是让人容易混淆的问题,下面我就来根据自己的理解来区分一下这两个传递方式: 值传递 值传递是两个变量传递前后互补干扰,无法造成影响,下面代码举例说明 var a=7; function fuc(a){ a++; } fuc(a) console.log(a); //7 向上面这样,当我们给a赋值之后,在通过调用函数调用吧a的值自增,但是改变的a的值只是在函数中...

lhxsirky的博客 920

JS的值传递和引用传递

JS中有5种基本数据类型,它们在赋值的时候是通过值传递,而引用数据类型(对象)是通过引用来传递. 举个例子: var x = 10; var y = 'abc'; var a = x; var b = y; a = 5; b = 'def'; console.log(x, y, a, b); // 10, 'abc', 5, 'def' 基本数据类型,改变a,b的值并没有影响x,y当我...

Hanhanyoona的博客 473

JS值传递和引用传递

方法的形式参数如果是一个基本数据类型,形式参数的改变对实际参数没有影响!(具体的数据值) 方法的形式参数如果是引用数据类型,形式参数的改变会直接影响实际参数!(地址和值) 值传递就是在函数调用中函数内部开辟了空间,结果函数没有改变到外部a的值,所有a的值还是10 var a = 10; console.log(a); //10 function fn(a){ a += 10; } ...

s1351295250的博客 247

JavaScript值传递和引用传递

值传递是只把对象的值传入函数,函数中可以使用这个值,但却无法更改该对象的值。 引用传递是将整个对象本身(或地址)传入函数,在函数中既可调用对象的值,也可改变对象的值。 复制变量 1. 基本类型 var num1 = 5; var num2 = num1; 2. 引用类型(对象) var obj1 = new Object(); var obj2 =

TianRangDeJieHuo的博客 380
上一篇: js参数转换,各种类型参数在另一种类型里代表什么
下一篇: 排序算法和分析史上最全
sells2012
博客等级 码龄15年 10粉丝 22原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值