В чем разница между & ldquo; Array () & rdquo; и & ldquo; [] & rdquo; при объявлении массива JavaScript?

В дополнение к M. Собственный простой и прагматичный ответ Дадли Более сжатая переформулировка ForNeVeR ):

Для удобства здесь представлена ​​расширенная функция Out-FileUtf8NoBom, альтернатива на основе трубопровода, которая имитирует Out-File, что означает:

  • вы можете использовать его так же, как Out-File в конвейере.
  • входные объекты, которые не являются строками, отформатированы так, как если бы они были, если вы отправили их на консоль, как с Out-File.

Пример:

(Get-Content $MyPath) | Out-FileUtf8NoBom $MyPath

Обратите внимание, что (Get-Content $MyPath) заключен в (...), который гарантирует, что весь файл будет открыт, прочитан полностью и закрыт перед отправкой результата по конвейеру. Это необходимо, чтобы иметь возможность записать обратно в тот же файл (обновите его на месте ). Как правило, этот метод не рекомендуется по двум причинам: (a) весь файл должен вписываться в память и (b) если команда прервана, данные будут потеряны.

Примечание об использовании памяти :

  • M. Собственный ответ Дадли требует, чтобы сначала было записано все содержимое файла в памяти, что может быть проблематичным для больших файлов.
  • Функция ниже улучшается только при этом: все входные объекты по-прежнему буферизуются во-первых, но их строковые представления затем сгенерированы и записываются в выходной файл один за другим.

Исходный код Out-FileUtf8NoBom (также доступен как лицензированный MIT Gist ):

<#
.SYNOPSIS
  Outputs to a UTF-8-encoded file *without a BOM* (byte-order mark).

.DESCRIPTION
  Mimics the most important aspects of Out-File:
  * Input objects are sent to Out-String first.
  * -Append allows you to append to an existing file, -NoClobber prevents
    overwriting of an existing file.
  * -Width allows you to specify the line width for the text representations
     of input objects that aren't strings.
  However, it is not a complete implementation of all Out-String parameters:
  * Only a literal output path is supported, and only as a parameter.
  * -Force is not supported.

  Caveat: *All* pipeline input is buffered before writing output starts,
          but the string representations are generated and written to the target
          file one by one.

.NOTES
  The raison d'être for this advanced function is that, as of PowerShell v5,
  Out-File still lacks the ability to write UTF-8 files without a BOM:
  using -Encoding UTF8 invariably prepends a BOM.

#>
function Out-FileUtf8NoBom {

  [CmdletBinding()]
  param(
    [Parameter(Mandatory, Position=0)] [string] $LiteralPath,
    [switch] $Append,
    [switch] $NoClobber,
    [AllowNull()] [int] $Width,
    [Parameter(ValueFromPipeline)] $InputObject
  )

  #requires -version 3

  # Make sure that the .NET framework sees the same working dir. as PS
  # and resolve the input path to a full path.
  [System.IO.Directory]::SetCurrentDirectory($PWD) # Caveat: .NET Core doesn't support [Environment]::CurrentDirectory
  $LiteralPath = [IO.Path]::GetFullPath($LiteralPath)

  # If -NoClobber was specified, throw an exception if the target file already
  # exists.
  if ($NoClobber -and (Test-Path $LiteralPath)) {
    Throw [IO.IOException] "The file '$LiteralPath' already exists."
  }

  # Create a StreamWriter object.
  # Note that we take advantage of the fact that the StreamWriter class by default:
  # - uses UTF-8 encoding
  # - without a BOM.
  $sw = New-Object IO.StreamWriter $LiteralPath, $Append

  $htOutStringArgs = @{}
  if ($Width) {
    $htOutStringArgs += @{ Width = $Width }
  }

  # Note: By not using begin / process / end blocks, we're effectively running
  #       in the end block, which means that all pipeline input has already
  #       been collected in automatic variable $Input.
  #       We must use this approach, because using | Out-String individually
  #       in each iteration of a process block would format each input object
  #       with an indvidual header.
  try {
    $Input | Out-String -Stream @htOutStringArgs | % { $sw.WriteLine($_) }
  } finally {
    $sw.Dispose()
  }

}

782
задан Mi-Creativity 25 December 2015 в 09:48
поделиться

5 ответов

There is a difference, but there is no difference in that example.

Using the more verbose method: new Array() does have one extra option in the parameters: if you pass a number to the constructor, you will get an array of that length:

x = new Array(5);
alert(x.length); // 5

To illustrate the different ways to create an array:

var a = [],            // these are the same
    b = new Array(),   // a and b are arrays with length 0

    c = ['foo', 'bar'],           // these are the same
    d = new Array('foo', 'bar'),  // c and d are arrays with 2 strings

    // these are different:
    e = [3]             // e.length == 1, e[0] == 3
    f = new Array(3),   // f.length == 3, f[0] == undefined

;

Another difference is that when using new Array() you're able to set the size of the array, which affects the stack size. This can be useful if you're getting stack overflows (Performance of Array.push vs Array.unshift) which is what happens when the size of the array exceeds the size of the stack, and it has to be re-created. So there can actually, depending on the use case, be a performance increase when using new Array() because you can prevent the overflow from happening.

As pointed out in this answer, new Array(5) will not actually add five undefined items to the array. It simply adds space for five items. Be aware that using Array this way makes it difficult to rely on array.length for calculations.

919
ответ дан 22 November 2019 в 21:17
поделиться

Первый - это вызов конструктора объекта по умолчанию. Вы можете использовать его параметры, если хотите.

var array = new Array(5); //initialize with default length 5

Второй дает вам возможность создать непустой массив:

var array = [1, 2, 3]; // this array will contain numbers 1, 2, 3.
8
ответ дан 22 November 2019 в 21:17
поделиться

For more information, the following page describes why you never need to use new Array()

You never need to use new Object() in JavaScript. Use the object literal {} instead. Similarly, don’t use new Array(), use the array literal [] instead. Arrays in JavaScript work nothing like the arrays in Java, and use of the Java-like syntax will confuse you.

Do not use new Number, new String, or new Boolean. These forms produce unnecessary object wrappers. Just use simple literals instead.

Also check out the comments - the new Array(length) form does not serve any useful purpose (at least in today's implementations of JavaScript).

39
ответ дан 22 November 2019 в 21:17
поделиться

Разница между созданием массива с неявным массивом и конструктором массива тонкая, но важная.

Когда вы создаете массив с помощью

var a = [];

, вы говорите интерпретатору создать новый массив времени выполнения. Никакой дополнительной обработки не требуется. Готово.

Если вы используете:

var a = new Array();

Вы говорите интерпретатору, я хочу вызвать конструктор « Array » и сгенерировать объект. Затем он просматривает ваш контекст выполнения, чтобы найти конструктор для вызова, и вызывает его, создавая ваш массив.

Вы можете подумать: «Ну, это вообще не имеет значения. Они такие же!». К сожалению, вы не можете этого гарантировать.

Возьмем следующий пример:

function Array() {
    this.is = 'SPARTA';
}

var a = new Array();
var b = [];

alert(a.is);  // => 'SPARTA'
alert(b.is);  // => undefined
a.push('Woa'); // => TypeError: a.push is not a function
b.push('Woa'); // => 1 (OK)

В приведенном выше примере первый вызов предупредит "SPARTA", как и следовало ожидать. Второго не будет. В конечном итоге вы увидите undefined. Вы также заметите, что b содержит все встроенные функции объекта Array, такие как push , тогда как другой - нет.

Хотя вы можете ожидать, что это произойдет, это просто иллюстрирует тот факт, что [] не то же самое, что new Array () .

Вероятно, лучше всего просто использовать [] , если вы знаете, что вам просто нужен массив. Я также не предлагаю переопределять Array ...

770
ответ дан 22 November 2019 в 21:17
поделиться

Как ни странно, new Array (size) почти в 2 раза быстрее, чем [] в Chrome, и примерно то же самое в FF и IE (измеряется путем создания и заполнения массива). Это имеет значение только в том случае, если вы знаете приблизительный размер массива. Если вы добавите больше элементов, чем указанная вами длина, прирост производительности будет потерян.

Точнее: Массив ( - это быстрая операция с постоянным временем, которая не выделяет память, тогда как [] - это линейная операция по времени, которая устанавливает тип и значение.

51
ответ дан 22 November 2019 в 21:17
поделиться
Другие вопросы по тегам:

Похожие вопросы: