如何解决将数组推入对象的问题?

时间:2019-06-18 11:33:08

标签: javascript arrays object

我正在研究基于文本的漫游器,目标是让2个不同的漫游器获取命令(turnLeft,turnRight,moveForward,moveBackwards)并在10x10网格中移动。此外,我想记录每个流动站的路径,这是我遇到麻烦的地方。我用两个键rover1和rover2创建了一个travelLog对象。每个键的值是一个初始化的数组[]。但是,当我尝试moveForward时,出现错误“ TypeError:无法读取未定义的属性” push”。

每个命令都接受一个参数(在本例中为流动站的名称:rover1或rover2)。由于登录同时在moveForward和moveBackwards函数中进行,所以我这样写:

 public void StartSpeechToText(ISpeechResultCallback callback)
    {

        string rec = global::Android.Content.PM.PackageManager.FeatureMicrophone;
        if (rec == "android.hardware.microphone")
        {
            MainActivity activity = MainActivity.CurrentActivity;
            activity.Callback = callback;

            var voiceIntent = new Intent(RecognizerIntent.ActionRecognizeSpeech);

            //var voiceIntent = new Intent(RecognizerIntent.ActionVoiceSearchHandsFree);

            voiceIntent.PutExtra(RecognizerIntent.ExtraLanguageModel, RecognizerIntent.LanguageModelFreeForm);

            voiceIntent.PutExtra(RecognizerIntent.ExtraPrompt, "Speak now");

            voiceIntent.PutExtra(RecognizerIntent.ExtraSpeechInputCompleteSilenceLengthMillis, 1500);
            voiceIntent.PutExtra(RecognizerIntent.ExtraSpeechInputPossiblyCompleteSilenceLengthMillis, 1500);
            voiceIntent.PutExtra(RecognizerIntent.ExtraSpeechInputMinimumLengthMillis, 15000);
            voiceIntent.PutExtra(RecognizerIntent.ExtraMaxResults, 1);
            voiceIntent.PutExtra(RecognizerIntent.ExtraLanguage, Java.Util.Locale.Default);

            activity.StartActivityForResult(voiceIntent, VOICE);


        }
    }

我希望将流动站的新位置记录到对象travelLog中,并位于其对应的键(rover1或rover2)中。

1 个答案:

答案 0 :(得分:3)

调用travelLog[rover]时,rover不是可以用作对象键的字符串。而是对象本身。
因此,您需要使用rover.name这样的流动站名称(它将为rover1),然后使用它:travelLog[rover.name]...


示例

const rover1 = {
  name: 'Bob',
  direction: 'N',
  x: 0,
  y: 0,
};

const rover2 = {
  name: 'Mike',
  direction: 'N',
  x: 5,
  y: 7,
};

let travelLog = {};

// ...

function moveForward(rover) {
  console.log("moveForward was called");
  if (!travelLog[rover.name]) {
    travelLog[rover.name] = [];
  }
  travelLog[rover.name].push(`Rover ${rover.name} moved to [x: ${rover.x},y ${rover.y}]`);

  // ...
}