JavaScript: использование кортежей как ключи словаря

Используйте "мишень" для перенаправления в файл и экран. В зависимости от оболочки Вы используете, сначала необходимо перенаправить stderr к stdout использование

./a.out 2>&1 | tee output

или

./a.out |& tee output

В csh, существует встроенная команда, названная "сценарием", который получит все, что переходит к экрану в файл. Вы запускаете его путем ввода "сценария", затем выполнения независимо от того, что это - Вы, хотят получить, затем поразить управление-D для закрытия файла сценария. Я не знаю об эквиваленте для sh/bash/ksh.

кроме того, так как Вы теперь указали, что это Ваши собственные sh сценарии, которые можно изменить, можно сделать перенаправление внутренне путем окружения целого сценария фигурными скобками или скобками, как

  #!/bin/sh
  {
    ... whatever you had in your script before
  } 2>&1 | tee output.file
29
задан hasen 15 September 2009 в 05:29
поделиться

3 ответа

EcmaScript doesn't distinguish between indexing a property by name or by [], eg.

a.name

is literally equivalent to

a["name"]

The only difference is that numbers, etc are not valid syntax in a named property access

a.1
a.true

and so on are all invalid syntax.

Alas the reason all of these indexing mechanisms are the same is because in EcmaScript all property names are strings. eg.

a[1]

is effectively interpreted as

a[String(1)]

Which means in your example you do:

my_map[[a,b]] = c

Which becomes

my_map[String([a,b])] = c

Which is essentially the same as what your second example is doing (depending on implementation it may be faster however).

If you want true value-associative lookups you will need to implement it yourself on top of the js language, and you'll lose the nice [] style access :-(

20
ответ дан 28 November 2019 в 02:03
поделиться

You could use my jshashtable and then use any object as a key, though assuming your tuples are arrays of integers I think your best bet is one you've mentioned yourself: use the join() method of Array to create property names of a regular object. You could wrap this very simply:

function TupleDictionary() {
 this.dict = {};
}

TupleDictionary.prototype = {
 tupleToString: function(tuple) {
  return tuple.join(",");
 },

 put: function(tuple, val) {
  this.dict[ this.tupleToString(tuple) ] = val;
 },

 get: function(tuple) {
  return this.dict[ this.tupleToString(tuple) ];
 }
};

var dict = new TupleDictionary();
dict.put( [1,2], "banana" );
alert( dict.get( [1,2] ) );
5
ответ дан 28 November 2019 в 02:03
поделиться

All object keys in Javascript are strings. Using my_map[[a,b]] = c will produce a key in my_map which is the result of [a,b].toString(): a.toString() + ',' + b.toString(). This may actually be desirable (and is similar to your use of a + ':' + b), but you may run into conflicts if your keys contain the separator (either the comma if you use the array as the key, or the colon if you write the string as you have in your example).

Edit: An alternate approach would be to keep a separate array for key references. Eg:

var keys = [
    [a,b],
    [c,d]
];
var my_map = {
    'keys[0]': /* Whatever [a,b] ought to be the key for */,
    'keys[1]': /* Whatever [c,d] ought to be the key for */
};
2
ответ дан 28 November 2019 в 02:03
поделиться
Другие вопросы по тегам:

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