うしブログ

うしブログ

趣味で運営する、GeoGebraの専門ブログ。

(作業メモ)StartPoint要検証(2行の場合;テキスト変更時未定義問題)

(要修復)ToggleButton・RollPolygonWithoutSlipping・貯金時計・直感力トレーニング

自由なリストオブジェクトの特定の要素のみにSetValueを実行するJavaScript

//リストの特定の要素にSetValueを実行する
function setElementValue(listName, index, value) {
    //フェイルセーフ
    if (!ggbApplet.exists(listName)) {
        alert('Error on function setElementValue: ' + listName + ' does not exist.');
        return;
    }

    if (!ggbApplet.isIndependent(listName)) {
        alert('Error on function setElementValue: ' + listName + ' is dependent.');
        return;
    }

    var length = ggbApplet.getValue('Length[' + listName + ']');
    index = parseInt(index);
    if (length < index) {
        alert('Error on function setElementValue: argument index must be ' + length + ' or less.');
        return;
    }
    if (!Number.isInteger(index) || index <= 0) {
        alert('Error on function setElementValue: argument index must be a natural number.');
        return;
    }

    //SetValueを実行
    ggbApplet.evalCommand('SetValue[' + listName + ',Join[Take[' + listName + ',1,' + index + '-1],{' + value + '},Take[' + listName + ',' + index + '+1]]]');
}

実質は最後の1行だけ。他はエラー回避用です。

なお、リストオブジェクトlistNameにおけるindex番目の要素の値を、valueにセットするためのGeoGebraスクリプトは、以下のとおりです。

SetValue[listName, Zip[If[IndexOf[s, listName] ≠ index, s, value], s, listName]]

上記JavaScriptは、このGeoGebraスクリプトを応用したものです。

使用例

自由なリストオブジェクトlist1={1,2,3,4,5}があるとする。

setElementValue('list1', 2, 0);

を実行すると、list1の2番目の要素が0にセットされる。その結果、list1の値は、

{1,0,3,4,5}

となる。